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 = 300; // integer; max paths with entries
28 /** @var Array Map of paths to large (RAM/disk) cache items */
29 protected $expensiveCache = array(); // (storage path => key => value)
30 protected $maxExpensiveCacheSize = 5; // integer; max paths with entries
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 // Recursive: first delete all empty subdirs recursively
388 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
389 $subDirsRel = $this->getTopDirectoryList( array( 'dir' => $params['dir'] ) );
390 if ( $subDirsRel !== null ) { // no errors
391 foreach ( $subDirsRel as $subDirRel ) {
392 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
393 $status->merge( $this->doClean( array( 'dir' => $subDir ) +
$params ) );
398 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
399 if ( $dir === null ) {
400 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
401 wfProfileOut( __METHOD__
. '-' . $this->name
);
402 wfProfileOut( __METHOD__
);
403 return $status; // invalid storage path
406 // Attempt to lock this directory...
407 $filesLockEx = array( $params['dir'] );
408 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
409 if ( !$status->isOK() ) {
410 wfProfileOut( __METHOD__
. '-' . $this->name
);
411 wfProfileOut( __METHOD__
);
412 return $status; // abort
415 if ( $shard !== null ) { // confined to a single container/shard
416 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
417 $this->deleteContainerCache( $fullCont ); // purge cache
418 } else { // directory is on several shards
419 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
420 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
421 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
422 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
423 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
427 wfProfileOut( __METHOD__
. '-' . $this->name
);
428 wfProfileOut( __METHOD__
);
433 * @see FileBackendStore::doClean()
436 protected function doCleanInternal( $container, $dir, array $params ) {
437 return Status
::newGood();
441 * @see FileBackend::fileExists()
444 final public function fileExists( array $params ) {
445 wfProfileIn( __METHOD__
);
446 wfProfileIn( __METHOD__
. '-' . $this->name
);
447 $stat = $this->getFileStat( $params );
448 wfProfileOut( __METHOD__
. '-' . $this->name
);
449 wfProfileOut( __METHOD__
);
450 return ( $stat === null ) ?
null : (bool)$stat; // null => failure
454 * @see FileBackend::getFileTimestamp()
457 final public function getFileTimestamp( array $params ) {
458 wfProfileIn( __METHOD__
);
459 wfProfileIn( __METHOD__
. '-' . $this->name
);
460 $stat = $this->getFileStat( $params );
461 wfProfileOut( __METHOD__
. '-' . $this->name
);
462 wfProfileOut( __METHOD__
);
463 return $stat ?
$stat['mtime'] : false;
467 * @see FileBackend::getFileSize()
470 final public function getFileSize( array $params ) {
471 wfProfileIn( __METHOD__
);
472 wfProfileIn( __METHOD__
. '-' . $this->name
);
473 $stat = $this->getFileStat( $params );
474 wfProfileOut( __METHOD__
. '-' . $this->name
);
475 wfProfileOut( __METHOD__
);
476 return $stat ?
$stat['size'] : false;
480 * @see FileBackend::getFileStat()
483 final public function getFileStat( array $params ) {
484 wfProfileIn( __METHOD__
);
485 wfProfileIn( __METHOD__
. '-' . $this->name
);
486 $path = self
::normalizeStoragePath( $params['src'] );
487 if ( $path === null ) {
488 wfProfileOut( __METHOD__
. '-' . $this->name
);
489 wfProfileOut( __METHOD__
);
490 return false; // invalid storage path
492 $latest = !empty( $params['latest'] );
493 if ( isset( $this->cache
[$path]['stat'] ) ) {
494 // If we want the latest data, check that this cached
495 // value was in fact fetched with the latest available data.
496 if ( !$latest ||
$this->cache
[$path]['stat']['latest'] ) {
497 $this->pingCache( $path ); // LRU
498 wfProfileOut( __METHOD__
. '-' . $this->name
);
499 wfProfileOut( __METHOD__
);
500 return $this->cache
[$path]['stat'];
503 wfProfileIn( __METHOD__
. '-miss' );
504 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
505 $stat = $this->doGetFileStat( $params );
506 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
507 wfProfileOut( __METHOD__
. '-miss' );
508 if ( is_array( $stat ) ) { // don't cache negatives
509 $this->trimCache(); // limit memory
510 $this->cache
[$path]['stat'] = $stat;
511 $this->cache
[$path]['stat']['latest'] = $latest;
513 wfProfileOut( __METHOD__
. '-' . $this->name
);
514 wfProfileOut( __METHOD__
);
519 * @see FileBackendStore::getFileStat()
521 abstract protected function doGetFileStat( array $params );
524 * @see FileBackend::getFileContents()
525 * @return bool|string
527 public function getFileContents( array $params ) {
528 wfProfileIn( __METHOD__
);
529 wfProfileIn( __METHOD__
. '-' . $this->name
);
530 $tmpFile = $this->getLocalReference( $params );
532 wfProfileOut( __METHOD__
. '-' . $this->name
);
533 wfProfileOut( __METHOD__
);
536 wfSuppressWarnings();
537 $data = file_get_contents( $tmpFile->getPath() );
539 wfProfileOut( __METHOD__
. '-' . $this->name
);
540 wfProfileOut( __METHOD__
);
545 * @see FileBackend::getFileSha1Base36()
546 * @return bool|string
548 final public function getFileSha1Base36( array $params ) {
549 wfProfileIn( __METHOD__
);
550 wfProfileIn( __METHOD__
. '-' . $this->name
);
551 $path = $params['src'];
552 if ( isset( $this->cache
[$path]['sha1'] ) ) {
553 $this->pingCache( $path ); // LRU
554 wfProfileOut( __METHOD__
. '-' . $this->name
);
555 wfProfileOut( __METHOD__
);
556 return $this->cache
[$path]['sha1'];
558 wfProfileIn( __METHOD__
. '-miss' );
559 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
560 $hash = $this->doGetFileSha1Base36( $params );
561 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
562 wfProfileOut( __METHOD__
. '-miss' );
563 if ( $hash ) { // don't cache negatives
564 $this->trimCache(); // limit memory
565 $this->cache
[$path]['sha1'] = $hash;
567 wfProfileOut( __METHOD__
. '-' . $this->name
);
568 wfProfileOut( __METHOD__
);
573 * @see FileBackendStore::getFileSha1Base36()
576 protected function doGetFileSha1Base36( array $params ) {
577 $fsFile = $this->getLocalReference( $params );
581 return $fsFile->getSha1Base36();
586 * @see FileBackend::getFileProps()
589 final public function getFileProps( array $params ) {
590 wfProfileIn( __METHOD__
);
591 wfProfileIn( __METHOD__
. '-' . $this->name
);
592 $fsFile = $this->getLocalReference( $params );
593 $props = $fsFile ?
$fsFile->getProps() : FSFile
::placeholderProps();
594 wfProfileOut( __METHOD__
. '-' . $this->name
);
595 wfProfileOut( __METHOD__
);
600 * @see FileBackend::getLocalReference()
601 * @return TempFSFile|null
603 public function getLocalReference( array $params ) {
604 wfProfileIn( __METHOD__
);
605 wfProfileIn( __METHOD__
. '-' . $this->name
);
606 $path = $params['src'];
607 if ( isset( $this->expensiveCache
[$path]['localRef'] ) ) {
608 $this->pingExpensiveCache( $path );
609 wfProfileOut( __METHOD__
. '-' . $this->name
);
610 wfProfileOut( __METHOD__
);
611 return $this->expensiveCache
[$path]['localRef'];
613 $tmpFile = $this->getLocalCopy( $params );
614 if ( $tmpFile ) { // don't cache negatives
615 $this->trimExpensiveCache(); // limit memory
616 $this->expensiveCache
[$path]['localRef'] = $tmpFile;
618 wfProfileOut( __METHOD__
. '-' . $this->name
);
619 wfProfileOut( __METHOD__
);
624 * @see FileBackend::streamFile()
627 final public function streamFile( array $params ) {
628 wfProfileIn( __METHOD__
);
629 wfProfileIn( __METHOD__
. '-' . $this->name
);
630 $status = Status
::newGood();
632 $info = $this->getFileStat( $params );
633 if ( !$info ) { // let StreamFile handle the 404
634 $status->fatal( 'backend-fail-notexists', $params['src'] );
637 // Set output buffer and HTTP headers for stream
638 $extraHeaders = isset( $params['headers'] ) ?
$params['headers'] : array();
639 $res = StreamFile
::prepareForStream( $params['src'], $info, $extraHeaders );
640 if ( $res == StreamFile
::NOT_MODIFIED
) {
641 // do nothing; client cache is up to date
642 } elseif ( $res == StreamFile
::READY_STREAM
) {
643 wfProfileIn( __METHOD__
. '-send' );
644 wfProfileIn( __METHOD__
. '-send-' . $this->name
);
645 $status = $this->doStreamFile( $params );
646 wfProfileOut( __METHOD__
. '-send-' . $this->name
);
647 wfProfileOut( __METHOD__
. '-send' );
649 $status->fatal( 'backend-fail-stream', $params['src'] );
652 wfProfileOut( __METHOD__
. '-' . $this->name
);
653 wfProfileOut( __METHOD__
);
658 * @see FileBackendStore::streamFile()
661 protected function doStreamFile( array $params ) {
662 $status = Status
::newGood();
664 $fsFile = $this->getLocalReference( $params );
666 $status->fatal( 'backend-fail-stream', $params['src'] );
667 } elseif ( !readfile( $fsFile->getPath() ) ) {
668 $status->fatal( 'backend-fail-stream', $params['src'] );
675 * @see FileBackend::directoryExists()
678 final public function directoryExists( array $params ) {
679 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
680 if ( $dir === null ) {
681 return false; // invalid storage path
683 if ( $shard !== null ) { // confined to a single container/shard
684 return $this->doDirectoryExists( $fullCont, $dir, $params );
685 } else { // directory is on several shards
686 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
687 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
688 $res = false; // response
689 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
690 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
694 } elseif ( $exists === null ) { // error?
695 $res = null; // if we don't find anything, it is indeterminate
703 * @see FileBackendStore::directoryExists()
705 * @param $container string Resolved container name
706 * @param $dir string Resolved path relative to container
707 * @param $params Array
710 abstract protected function doDirectoryExists( $container, $dir, array $params );
713 * @see FileBackend::getDirectoryList()
714 * @return Traversable|Array|null Returns null on failure
716 final public function getDirectoryList( array $params ) {
717 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
718 if ( $dir === null ) { // invalid storage path
721 if ( $shard !== null ) {
722 // File listing is confined to a single container/shard
723 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
725 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
726 // File listing spans multiple containers/shards
727 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
728 return new FileBackendStoreShardDirIterator( $this,
729 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
734 * Do not call this function from places outside FileBackend
736 * @see FileBackendStore::getDirectoryList()
738 * @param $container string Resolved container name
739 * @param $dir string Resolved path relative to container
740 * @param $params Array
741 * @return Traversable|Array|null Returns null on failure
743 abstract public function getDirectoryListInternal( $container, $dir, array $params );
746 * @see FileBackend::getFileList()
747 * @return Traversable|Array|null Returns null on failure
749 final public function getFileList( array $params ) {
750 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
751 if ( $dir === null ) { // invalid storage path
754 if ( $shard !== null ) {
755 // File listing is confined to a single container/shard
756 return $this->getFileListInternal( $fullCont, $dir, $params );
758 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
759 // File listing spans multiple containers/shards
760 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
761 return new FileBackendStoreShardFileIterator( $this,
762 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
767 * Do not call this function from places outside FileBackend
769 * @see FileBackendStore::getFileList()
771 * @param $container string Resolved container name
772 * @param $dir string Resolved path relative to container
773 * @param $params Array
774 * @return Traversable|Array|null Returns null on failure
776 abstract public function getFileListInternal( $container, $dir, array $params );
779 * Get the list of supported operations and their corresponding FileOp classes.
783 protected function supportedOperations() {
785 'store' => 'StoreFileOp',
786 'copy' => 'CopyFileOp',
787 'move' => 'MoveFileOp',
788 'delete' => 'DeleteFileOp',
789 'create' => 'CreateFileOp',
790 'null' => 'NullFileOp'
795 * Return a list of FileOp objects from a list of operations.
796 * Do not call this function from places outside FileBackend.
798 * The result must have the same number of items as the input.
799 * An exception is thrown if an unsupported operation is requested.
801 * @param $ops Array Same format as doOperations()
802 * @return Array List of FileOp objects
803 * @throws MWException
805 final public function getOperationsInternal( array $ops ) {
806 $supportedOps = $this->supportedOperations();
808 $performOps = array(); // array of FileOp objects
809 // Build up ordered array of FileOps...
810 foreach ( $ops as $operation ) {
811 $opName = $operation['op'];
812 if ( isset( $supportedOps[$opName] ) ) {
813 $class = $supportedOps[$opName];
814 // Get params for this operation
815 $params = $operation;
816 // Append the FileOp class
817 $performOps[] = new $class( $this, $params );
819 throw new MWException( "Operation '$opName' is not supported." );
827 * Get a list of storage paths to lock for a list of operations
828 * Returns an array with 'sh' (shared) and 'ex' (exclusive) keys,
829 * each corresponding to a list of storage paths to be locked.
831 * @param $performOps Array List of FileOp objects
832 * @return Array ('sh' => list of paths, 'ex' => list of paths)
834 final public function getPathsToLockForOpsInternal( array $performOps ) {
835 // Build up a list of files to lock...
836 $paths = array( 'sh' => array(), 'ex' => array() );
837 foreach ( $performOps as $fileOp ) {
838 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
839 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
841 // Optimization: if doing an EX lock anyway, don't also set an SH one
842 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
843 // Get a shared lock on the parent directory of each path changed
844 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
850 * @see FileBackend::doOperationsInternal()
853 protected function doOperationsInternal( array $ops, array $opts ) {
854 wfProfileIn( __METHOD__
);
855 wfProfileIn( __METHOD__
. '-' . $this->name
);
856 $status = Status
::newGood();
858 // Build up a list of FileOps...
859 $performOps = $this->getOperationsInternal( $ops );
861 // Acquire any locks as needed...
862 if ( empty( $opts['nonLocking'] ) ) {
863 // Build up a list of files to lock...
864 $paths = $this->getPathsToLockForOpsInternal( $performOps );
865 // Try to lock those files for the scope of this function...
866 $scopeLockS = $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status );
867 $scopeLockE = $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status );
868 if ( !$status->isOK() ) {
869 wfProfileOut( __METHOD__
. '-' . $this->name
);
870 wfProfileOut( __METHOD__
);
871 return $status; // abort
875 // Clear any file cache entries (after locks acquired)
878 // Load from the persistent container cache
879 $this->primeContainerCache( $performOps );
881 // Actually attempt the operation batch...
882 $subStatus = FileOp
::attemptBatch( $performOps, $opts, $this->fileJournal
);
884 // Merge errors into status fields
885 $status->merge( $subStatus );
886 $status->success
= $subStatus->success
; // not done in merge()
888 wfProfileOut( __METHOD__
. '-' . $this->name
);
889 wfProfileOut( __METHOD__
);
894 * @see FileBackend::clearCache()
896 final public function clearCache( array $paths = null ) {
897 if ( is_array( $paths ) ) {
898 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
899 $paths = array_filter( $paths, 'strlen' ); // remove nulls
901 if ( $paths === null ) {
902 $this->cache
= array();
903 $this->expensiveCache
= array();
905 foreach ( $paths as $path ) {
906 unset( $this->cache
[$path] );
907 unset( $this->expensiveCache
[$path] );
910 $this->doClearCache( $paths );
914 * Clears any additional stat caches for storage paths
916 * @see FileBackend::clearCache()
918 * @param $paths Array Storage paths (optional)
921 protected function doClearCache( array $paths = null ) {}
924 * Is this a key/value store where directories are just virtual?
925 * Virtual directories exists in so much as files exists that are
926 * prefixed with the directory path followed by a forward slash.
930 abstract protected function directoriesAreVirtual();
933 * Move a cache entry to the top (such as when accessed)
935 * @param $path string Storage path
938 protected function pingCache( $path ) {
939 if ( isset( $this->cache
[$path] ) ) {
940 $tmp = $this->cache
[$path];
941 unset( $this->cache
[$path] );
942 $this->cache
[$path] = $tmp;
947 * Prune the inexpensive cache if it is too big to add an item
951 protected function trimCache() {
952 if ( count( $this->cache
) >= $this->maxCacheSize
) {
953 reset( $this->cache
);
954 unset( $this->cache
[key( $this->cache
)] );
959 * Move a cache entry to the top (such as when accessed)
961 * @param $path string Storage path
964 protected function pingExpensiveCache( $path ) {
965 if ( isset( $this->expensiveCache
[$path] ) ) {
966 $tmp = $this->expensiveCache
[$path];
967 unset( $this->expensiveCache
[$path] );
968 $this->expensiveCache
[$path] = $tmp;
973 * Prune the expensive cache if it is too big to add an item
977 protected function trimExpensiveCache() {
978 if ( count( $this->expensiveCache
) >= $this->maxExpensiveCacheSize
) {
979 reset( $this->expensiveCache
);
980 unset( $this->expensiveCache
[key( $this->expensiveCache
)] );
985 * Check if a container name is valid.
986 * This checks for for length and illegal characters.
988 * @param $container string
991 final protected static function isValidContainerName( $container ) {
992 // This accounts for Swift and S3 restrictions while leaving room
993 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
994 // This disallows directory separators or traversal characters.
995 // Note that matching strings URL encode to the same string;
996 // in Swift, the length restriction is *after* URL encoding.
997 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1001 * Splits a storage path into an internal container name,
1002 * an internal relative file name, and a container shard suffix.
1003 * Any shard suffix is already appended to the internal container name.
1004 * This also checks that the storage path is valid and within this backend.
1006 * If the container is sharded but a suffix could not be determined,
1007 * this means that the path can only refer to a directory and can only
1008 * be scanned by looking in all the container shards.
1010 * @param $storagePath string
1011 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1013 final protected function resolveStoragePath( $storagePath ) {
1014 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1015 if ( $backend === $this->name
) { // must be for this backend
1016 $relPath = self
::normalizeContainerPath( $relPath );
1017 if ( $relPath !== null ) {
1018 // Get shard for the normalized path if this container is sharded
1019 $cShard = $this->getContainerShard( $container, $relPath );
1020 // Validate and sanitize the relative path (backend-specific)
1021 $relPath = $this->resolveContainerPath( $container, $relPath );
1022 if ( $relPath !== null ) {
1023 // Prepend any wiki ID prefix to the container name
1024 $container = $this->fullContainerName( $container );
1025 if ( self
::isValidContainerName( $container ) ) {
1026 // Validate and sanitize the container name (backend-specific)
1027 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1028 if ( $container !== null ) {
1029 return array( $container, $relPath, $cShard );
1035 return array( null, null, null );
1039 * Like resolveStoragePath() except null values are returned if
1040 * the container is sharded and the shard could not be determined.
1042 * @see FileBackendStore::resolveStoragePath()
1044 * @param $storagePath string
1045 * @return Array (container, path) or (null, null) if invalid
1047 final protected function resolveStoragePathReal( $storagePath ) {
1048 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1049 if ( $cShard !== null ) {
1050 return array( $container, $relPath );
1052 return array( null, null );
1056 * Get the container name shard suffix for a given path.
1057 * Any empty suffix means the container is not sharded.
1059 * @param $container string Container name
1060 * @param $relStoragePath string Storage path relative to the container
1061 * @return string|null Returns null if shard could not be determined
1063 final protected function getContainerShard( $container, $relPath ) {
1064 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1065 if ( $levels == 1 ||
$levels == 2 ) {
1066 // Hash characters are either base 16 or 36
1067 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1068 // Get a regex that represents the shard portion of paths.
1069 // The concatenation of the captures gives us the shard.
1070 if ( $levels === 1 ) { // 16 or 36 shards per container
1071 $hashDirRegex = '(' . $char . ')';
1072 } else { // 256 or 1296 shards per container
1073 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1074 $hashDirRegex = $char . '/(' . $char . '{2})';
1075 } else { // short hash dir format (e.g. "a/b/c")
1076 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1079 // Allow certain directories to be above the hash dirs so as
1080 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1081 // They must be 2+ chars to avoid any hash directory ambiguity.
1083 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1084 return '.' . implode( '', array_slice( $m, 1 ) );
1086 return null; // failed to match
1088 return ''; // no sharding
1092 * Check if a storage path maps to a single shard.
1093 * Container dirs like "a", where the container shards on "x/xy",
1094 * can reside on several shards. Such paths are tricky to handle.
1096 * @param $storagePath string Storage path
1099 final public function isSingleShardPathInternal( $storagePath ) {
1100 list( $c, $r, $shard ) = $this->resolveStoragePath( $storagePath );
1101 return ( $shard !== null );
1105 * Get the sharding config for a container.
1106 * If greater than 0, then all file storage paths within
1107 * the container are required to be hashed accordingly.
1109 * @param $container string
1110 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
1112 final protected function getContainerHashLevels( $container ) {
1113 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1114 $config = $this->shardViaHashLevels
[$container];
1115 $hashLevels = (int)$config['levels'];
1116 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1117 $hashBase = (int)$config['base'];
1118 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1119 return array( $hashLevels, $hashBase, $config['repeat'] );
1123 return array( 0, 0, false ); // no sharding
1127 * Get a list of full container shard suffixes for a container
1129 * @param $container string
1132 final protected function getContainerSuffixes( $container ) {
1134 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1135 if ( $digits > 0 ) {
1136 $numShards = pow( $base, $digits );
1137 for ( $index = 0; $index < $numShards; $index++
) {
1138 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1145 * Get the full container name, including the wiki ID prefix
1147 * @param $container string
1150 final protected function fullContainerName( $container ) {
1151 if ( $this->wikiId
!= '' ) {
1152 return "{$this->wikiId}-$container";
1159 * Resolve a container name, checking if it's allowed by the backend.
1160 * This is intended for internal use, such as encoding illegal chars.
1161 * Subclasses can override this to be more restrictive.
1163 * @param $container string
1164 * @return string|null
1166 protected function resolveContainerName( $container ) {
1171 * Resolve a relative storage path, checking if it's allowed by the backend.
1172 * This is intended for internal use, such as encoding illegal chars or perhaps
1173 * getting absolute paths (e.g. FS based backends). Note that the relative path
1174 * may be the empty string (e.g. the path is simply to the container).
1176 * @param $container string Container name
1177 * @param $relStoragePath string Storage path relative to the container
1178 * @return string|null Path or null if not valid
1180 protected function resolveContainerPath( $container, $relStoragePath ) {
1181 return $relStoragePath;
1185 * Get the cache key for a container
1187 * @param $container Resolved container name
1190 private function containerCacheKey( $container ) {
1191 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1195 * Set the cached info for a container
1197 * @param $container Resolved container name
1198 * @param $val mixed Information to cache
1201 final protected function setContainerCache( $container, $val ) {
1202 $this->memCache
->set( $this->containerCacheKey( $container ), $val, 7*86400 );
1206 * Delete the cached info for a container
1208 * @param $container Resolved container name
1211 final protected function deleteContainerCache( $container ) {
1212 $this->memCache
->delete( $this->containerCacheKey( $container ) );
1216 * Do a batch lookup from cache for container stats for all containers
1217 * used in a list of container names, storage paths, or FileOp objects.
1219 * @param $items Array List of storage paths or FileOps
1222 final protected function primeContainerCache( array $items ) {
1223 $paths = array(); // list of storage paths
1224 $contNames = array(); // (cache key => resolved container name)
1225 // Get all the paths/containers from the items...
1226 foreach ( $items as $item ) {
1227 if ( $item instanceof FileOp
) {
1228 $paths = array_merge( $paths, $item->storagePathsRead() );
1229 $paths = array_merge( $paths, $item->storagePathsChanged() );
1230 } elseif ( self
::isStoragePath( $item ) ) {
1232 } elseif ( is_string( $item ) ) { // full container name
1233 $contNames[$this->containerCacheKey( $item )] = $item;
1236 // Get all the corresponding cache keys for paths...
1237 foreach ( $paths as $path ) {
1238 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1239 if ( $fullCont !== null ) { // valid path for this backend
1240 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1244 $contInfo = array(); // (resolved container name => cache value)
1245 // Get all cache entries for these container cache keys...
1246 $values = $this->memCache
->getBatch( array_keys( $contNames ) );
1247 foreach ( $values as $cacheKey => $val ) {
1248 $contInfo[$contNames[$cacheKey]] = $val;
1251 // Populate the container process cache for the backend...
1252 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1256 * Fill the backend-specific process cache given an array of
1257 * resolved container names and their corresponding cached info.
1258 * Only containers that actually exist should appear in the map.
1260 * @param $containerInfo Array Map of resolved container names to cached info
1263 protected function doPrimeContainerCache( array $containerInfo ) {}
1267 * FileBackendStore helper function to handle listings that span container shards.
1268 * Do not use this class from places outside of FileBackendStore.
1270 * @ingroup FileBackend
1272 abstract class FileBackendStoreShardListIterator
implements Iterator
{
1273 /** @var FileBackendStore */
1278 protected $shardSuffixes;
1279 protected $container; // string; full container name
1280 protected $directory; // string; resolved relative path
1282 /** @var Traversable */
1284 protected $curShard = 0; // integer
1285 protected $pos = 0; // integer
1288 protected $multiShardPaths = array(); // (rel path => 1)
1291 * @param $backend FileBackendStore
1292 * @param $container string Full storage container name
1293 * @param $dir string Storage directory relative to container
1294 * @param $suffixes Array List of container shard suffixes
1295 * @param $params Array
1297 public function __construct(
1298 FileBackendStore
$backend, $container, $dir, array $suffixes, array $params
1300 $this->backend
= $backend;
1301 $this->container
= $container;
1302 $this->directory
= $dir;
1303 $this->shardSuffixes
= $suffixes;
1304 $this->params
= $params;
1308 * @see Iterator::current()
1309 * @return string|bool String or false
1311 public function current() {
1312 if ( is_array( $this->iter
) ) {
1313 return current( $this->iter
);
1315 return $this->iter
->current();
1320 * @see Iterator::key()
1323 public function key() {
1328 * @see Iterator::next()
1331 public function next() {
1333 if ( is_array( $this->iter
) ) {
1334 next( $this->iter
);
1336 $this->iter
->next();
1338 // Filter out items that we already listed
1339 $this->filterViaNext();
1340 // Find the next non-empty shard if no elements are left
1341 $this->nextShardIteratorIfNotValid();
1345 * @see Iterator::rewind()
1348 public function rewind() {
1350 $this->curShard
= 0;
1351 $this->setIteratorFromCurrentShard();
1352 // Filter out items that we already listed
1353 $this->filterViaNext();
1354 // Find the next non-empty shard if this one has no elements
1355 $this->nextShardIteratorIfNotValid();
1359 * @see Iterator::valid()
1362 public function valid() {
1363 if ( $this->iter
=== null ) {
1364 return false; // some failure?
1365 } elseif ( is_array( $this->iter
) ) {
1366 return ( current( $this->iter
) !== false ); // no paths can have this value
1368 return $this->iter
->valid();
1373 * Filter out duplicate items by advancing to the next ones
1375 protected function filterViaNext() {
1376 while ( $this->iter
->valid() ) {
1377 $rel = $this->iter
->current(); // path relative to given directory
1378 $path = $this->params
['dir'] . "/{$rel}"; // full storage path
1379 if ( !$this->backend
->isSingleShardPathInternal( $path ) ) {
1380 // Don't keep listing paths that are on multiple shards
1381 if ( isset( $this->multiShardPaths
[$rel] ) ) {
1382 $this->iter
->next(); // we already listed this path
1384 $this->multiShardPaths
[$rel] = 1;
1392 * If the list iterator for this container shard is out of items,
1393 * then move on to the next container that has items.
1394 * If there are none, then it advances to the last container.
1396 protected function nextShardIteratorIfNotValid() {
1397 while ( !$this->valid() ) {
1398 if ( ++
$this->curShard
>= count( $this->shardSuffixes
) ) {
1399 break; // no more container shards
1401 $this->setIteratorFromCurrentShard();
1406 * Set the list iterator to that of the current container shard
1408 protected function setIteratorFromCurrentShard() {
1409 $suffix = $this->shardSuffixes
[$this->curShard
];
1410 $this->iter
= $this->listFromShard(
1411 "{$this->container}{$suffix}", $this->directory
, $this->params
);
1415 * Get the list for a given container shard
1417 * @param $container string Resolved container name
1418 * @param $dir string Resolved path relative to container
1419 * @param $params Array
1420 * @return Traversable|Array|null
1422 abstract protected function listFromShard( $container, $dir, array $params );
1426 * Iterator for listing directories
1428 class FileBackendStoreShardDirIterator
extends FileBackendStoreShardListIterator
{
1429 protected function listFromShard( $container, $dir, array $params ) {
1430 return $this->backend
->getDirectoryListInternal( $container, $dir, $params );
1435 * Iterator for listing regular files
1437 class FileBackendStoreShardFileIterator
extends FileBackendStoreShardListIterator
{
1438 protected function listFromShard( $container, $dir, array $params ) {
1439 return $this->backend
->getFileListInternal( $container, $dir, $params );