9 * Base class for all file backend classes (including multi-write backends).
10 * This class defines the methods as abstract that subclasses must implement.
11 * Outside callers can assume that all backends will have these functions.
13 * All "storage paths" are of the format "mwstore://backend/container/path".
14 * The paths use UNIX file system (FS) notation, though any particular backend may
15 * not actually be using a local filesystem. Therefore, the paths are only virtual.
17 * Backend contents are stored under wiki-specific container names by default.
18 * For legacy reasons, this has no effect for the FS backend class, and per-wiki
19 * segregation must be done by setting the container paths appropriately.
21 * FS-based backends are somewhat more restrictive due to the existence of real
22 * directory files; a regular file cannot have the same name as a directory. Other
23 * backends with virtual directories may not have this limitation. Callers should
24 * store files in such a way that no files and directories are under the same path.
26 * Methods should avoid throwing exceptions at all costs.
27 * As a corollary, external dependencies should be kept to a minimum.
29 * @ingroup FileBackend
32 abstract class FileBackendBase
{
33 protected $name; // unique backend name
34 protected $wikiId; // unique wiki name
35 protected $readOnly; // string
36 /** @var LockManager */
37 protected $lockManager;
40 * Create a new backend instance from configuration.
41 * This should only be called from within FileBackendGroup.
44 * 'name' : The unique name of this backend.
45 * 'wikiId' : Prefix to container names that is unique to this wiki.
46 * This should consist of alphanumberic, '-', and '_' chars.
47 * 'lockManager' : Registered name of a file lock manager to use.
48 * 'readOnly' : Write operations are disallowed if this is a non-empty string.
49 * It should be an explanation for the backend being read-only.
51 * @param $config Array
53 public function __construct( array $config ) {
54 $this->name
= $config['name'];
55 $this->wikiId
= isset( $config['wikiId'] )
57 : wfWikiID(); // e.g. "my_wiki-en_"
58 $this->wikiId
= $this->resolveWikiId( $this->wikiId
);
59 $this->lockManager
= LockManagerGroup
::singleton()->get( $config['lockManager'] );
60 $this->readOnly
= isset( $config['readOnly'] )
61 ?
(string)$config['readOnly']
66 * Normalize a wiki ID by replacing characters that are
67 * not supported by the backend as part of container names.
69 * @param $wikiId string
72 protected function resolveWikiId( $wikiId ) {
77 * Get the unique backend name.
79 * We may have multiple different backends of the same type.
80 * For example, we can have two Swift backends using different proxies.
84 final public function getName() {
89 * This is the main entry point into the backend for write operations.
90 * Callers supply an ordered list of operations to perform as a transaction.
91 * If any serious errors occur, all attempted operations will be rolled back.
93 * $ops is an array of arrays. The outer array holds a list of operations.
94 * Each inner array is a set of key value pairs that specify an operation.
96 * Supported operations and their parameters:
97 * a) Create a new file in storage with the contents of a string
100 * 'dst' => <storage path>,
101 * 'content' => <string of new file contents>,
102 * 'overwriteDest' => <boolean>,
103 * 'overwriteSame' => <boolean>
105 * b) Copy a file system file into storage
108 * 'src' => <file system path>,
109 * 'dst' => <storage path>,
110 * 'overwriteDest' => <boolean>,
111 * 'overwriteSame' => <boolean>
113 * c) Copy a file within storage
116 * 'src' => <storage path>,
117 * 'dst' => <storage path>,
118 * 'overwriteDest' => <boolean>,
119 * 'overwriteSame' => <boolean>
121 * d) Move a file within storage
124 * 'src' => <storage path>,
125 * 'dst' => <storage path>,
126 * 'overwriteDest' => <boolean>,
127 * 'overwriteSame' => <boolean>
129 * e) Delete a file within storage
132 * 'src' => <storage path>,
133 * 'ignoreMissingSource' => <boolean>
135 * f) Do nothing (no-op)
140 * Boolean flags for operations (operation-specific):
141 * 'ignoreMissingSource' : The operation will simply succeed and do
142 * nothing if the source file does not exist.
143 * 'overwriteDest' : Any destination file will be overwritten.
144 * 'overwriteSame' : An error will not be given if a file already
145 * exists at the destination that has the same
146 * contents as the new contents to be written there.
148 * $opts is an associative of boolean flags, including:
149 * 'force' : Errors that would normally cause a rollback do not.
150 * The remaining operations are still attempted if any fail.
151 * 'nonLocking' : No locks are acquired for the operations.
152 * This can increase performance for non-critical writes.
153 * This has no effect unless the 'force' flag is set.
154 * 'allowStale' : Don't require the latest available data.
155 * This can increase performance for non-critical writes.
156 * This has no effect unless the 'force' flag is set.
159 * This returns a Status, which contains all warnings and fatals that occured
160 * during the operation. The 'failCount', 'successCount', and 'success' members
161 * will reflect each operation attempted. The status will be "OK" unless any
162 * of the operations failed and the 'force' parameter was not set.
164 * @param $ops Array List of operations to execute in order
165 * @param $opts Array Batch operation options
168 final public function doOperations( array $ops, array $opts = array() ) {
169 if ( $this->readOnly
!= '' ) {
170 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
172 if ( empty( $opts['force'] ) ) { // sanity
173 unset( $opts['nonLocking'] );
174 unset( $opts['allowStale'] );
176 return $this->doOperationsInternal( $ops, $opts );
180 * @see FileBackendBase::doOperations()
182 abstract protected function doOperationsInternal( array $ops, array $opts );
185 * Same as doOperations() except it takes a single operation.
186 * If you are doing a batch of operations that should either
187 * all succeed or all fail, then use that function instead.
189 * @see FileBackendBase::doOperations()
191 * @param $op Array Operation
192 * @param $opts Array Operation options
195 final public function doOperation( array $op, array $opts = array() ) {
196 return $this->doOperations( array( $op ), $opts );
200 * Performs a single create operation.
201 * This sets $params['op'] to 'create' and passes it to doOperation().
203 * @see FileBackendBase::doOperation()
205 * @param $params Array Operation parameters
206 * @param $opts Array Operation options
209 final public function create( array $params, array $opts = array() ) {
210 $params['op'] = 'create';
211 return $this->doOperation( $params, $opts );
215 * Performs a single store operation.
216 * This sets $params['op'] to 'store' and passes it to doOperation().
218 * @see FileBackendBase::doOperation()
220 * @param $params Array Operation parameters
221 * @param $opts Array Operation options
224 final public function store( array $params, array $opts = array() ) {
225 $params['op'] = 'store';
226 return $this->doOperation( $params, $opts );
230 * Performs a single copy operation.
231 * This sets $params['op'] to 'copy' and passes it to doOperation().
233 * @see FileBackendBase::doOperation()
235 * @param $params Array Operation parameters
236 * @param $opts Array Operation options
239 final public function copy( array $params, array $opts = array() ) {
240 $params['op'] = 'copy';
241 return $this->doOperation( $params, $opts );
245 * Performs a single move operation.
246 * This sets $params['op'] to 'move' and passes it to doOperation().
248 * @see FileBackendBase::doOperation()
250 * @param $params Array Operation parameters
251 * @param $opts Array Operation options
254 final public function move( array $params, array $opts = array() ) {
255 $params['op'] = 'move';
256 return $this->doOperation( $params, $opts );
260 * Performs a single delete operation.
261 * This sets $params['op'] to 'delete' and passes it to doOperation().
263 * @see FileBackendBase::doOperation()
265 * @param $params Array Operation parameters
266 * @param $opts Array Operation options
269 final public function delete( array $params, array $opts = array() ) {
270 $params['op'] = 'delete';
271 return $this->doOperation( $params, $opts );
275 * Concatenate a list of storage files into a single file on the file system
277 * srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
278 * dst : file system path to 0-byte temp file
280 * @param $params Array Operation parameters
283 abstract public function concatenate( array $params );
286 * Prepare a storage path for usage. This will create containers
287 * that don't yet exist or, on FS backends, create parent directories.
290 * dir : storage directory
292 * @param $params Array
295 abstract public function prepare( array $params );
298 * Take measures to block web access to a directory and
299 * the container it belongs to. FS backends might add .htaccess
300 * files wheras backends like Swift this might restrict container
301 * access to backend user that represents end-users in web request.
302 * This is not guaranteed to actually do anything.
305 * dir : storage directory
306 * noAccess : try to deny file access
307 * noListing : try to deny file listing
309 * @param $params Array
312 abstract public function secure( array $params );
315 * Clean up an empty storage directory.
316 * On FS backends, the directory will be deleted. Others may do nothing.
319 * dir : storage directory
321 * @param $params Array
324 abstract public function clean( array $params );
327 * Check if a file exists at a storage path in the backend.
328 * This returns false if only a directory exists at the path.
331 * src : source storage path
332 * latest : use the latest available data
334 * @param $params Array
335 * @return bool|null Returns null on failure
337 abstract public function fileExists( array $params );
340 * Get the last-modified timestamp of the file at a storage path.
343 * src : source storage path
344 * latest : use the latest available data
346 * @param $params Array
347 * @return string|false TS_MW timestamp or false on failure
349 abstract public function getFileTimestamp( array $params );
352 * Get the contents of a file at a storage path in the backend.
353 * This should be avoided for potentially large files.
356 * src : source storage path
357 * latest : use the latest available data
359 * @param $params Array
360 * @return string|false Returns false on failure
362 abstract public function getFileContents( array $params );
365 * Get the size (bytes) of a file at a storage path in the backend.
368 * src : source storage path
369 * latest : use the latest available data
371 * @param $params Array
372 * @return integer|false Returns false on failure
374 abstract public function getFileSize( array $params );
377 * Get quick information about a file at a storage path in the backend.
378 * The result is an associative array that includes:
379 * mtime : the last-modified timestamp (TS_MW) or false
380 * size : the file size (bytes) or false
383 * src : source storage path
384 * latest : use the latest available data
386 * @param $params Array
387 * @return Array|false Returns false on failure
389 abstract public function getFileStat( array $params );
392 * Get a SHA-1 hash of the file at a storage path in the backend.
395 * src : source storage path
396 * latest : use the latest available data
398 * @param $params Array
399 * @return string|false Hash string or false on failure
401 abstract public function getFileSha1Base36( array $params );
404 * Get the properties of the file at a storage path in the backend.
405 * Returns FSFile::placeholderProps() on failure.
408 * src : source storage path
409 * latest : use the latest available data
411 * @param $params Array
414 abstract public function getFileProps( array $params );
417 * Stream the file at a storage path in the backend.
418 * If the file does not exists, a 404 error will be given.
419 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
420 * must be sent if streaming began, while none should be sent otherwise.
421 * Implementations should flush the output buffer before sending data.
424 * src : source storage path
425 * headers : additional HTTP headers to send on success
426 * latest : use the latest available data
428 * @param $params Array
431 abstract public function streamFile( array $params );
434 * Returns a file system file, identical to the file at a storage path.
435 * The file returned is either:
436 * a) A local copy of the file at a storage path in the backend.
437 * The temporary copy will have the same extension as the source.
438 * b) An original of the file at a storage path in the backend.
439 * Temporary files may be purged when the file object falls out of scope.
441 * Write operations should *never* be done on this file as some backends
442 * may do internal tracking or may be instances of FileBackendMultiWrite.
443 * In that later case, there are copies of the file that must stay in sync.
446 * src : source storage path
447 * latest : use the latest available data
449 * @param $params Array
450 * @return FSFile|null Returns null on failure
452 abstract public function getLocalReference( array $params );
455 * Get a local copy on disk of the file at a storage path in the backend.
456 * The temporary copy will have the same file extension as the source.
457 * Temporary files may be purged when the file object falls out of scope.
460 * src : source storage path
461 * latest : use the latest available data
463 * @param $params Array
464 * @return TempFSFile|null Returns null on failure
466 abstract public function getLocalCopy( array $params );
469 * Get an iterator to list out all stored files under a storage directory.
470 * If the directory is of the form "mwstore://container", then all items in
471 * the container should be listed. If of the form "mwstore://container/dir",
472 * then all items under that container directory should be listed.
473 * Results should be storage paths relative to the given directory.
476 * dir : storage path directory
478 * @return Traversable|Array|null Returns null on failure
480 abstract public function getFileList( array $params );
483 * Invalidate any in-process file existence and property cache.
484 * If $paths is given, then only the cache for those files will be cleared.
486 * @param $paths Array Storage paths
489 abstract public function clearCache( array $paths = null );
492 * Lock the files at the given storage paths in the backend.
493 * This will either lock all the files or none (on failure).
495 * Callers should consider using getScopedFileLocks() instead.
497 * @param $paths Array Storage paths
498 * @param $type integer LockManager::LOCK_* constant
501 final public function lockFiles( array $paths, $type ) {
502 return $this->lockManager
->lock( $paths, $type );
506 * Unlock the files at the given storage paths in the backend.
508 * @param $paths Array Storage paths
509 * @param $type integer LockManager::LOCK_* constant
512 final public function unlockFiles( array $paths, $type ) {
513 return $this->lockManager
->unlock( $paths, $type );
517 * Lock the files at the given storage paths in the backend.
518 * This will either lock all the files or none (on failure).
519 * On failure, the status object will be updated with errors.
521 * Once the return value goes out scope, the locks will be released and
522 * the status updated. Unlock fatals will not change the status "OK" value.
524 * @param $paths Array Storage paths
525 * @param $type integer LockManager::LOCK_* constant
526 * @param $status Status Status to update on lock/unlock
527 * @return ScopedLock|null Returns null on failure
529 final public function getScopedFileLocks( array $paths, $type, Status
$status ) {
530 return ScopedLock
::factory( $this->lockManager
, $paths, $type, $status );
535 * Base class for all single-write backends.
536 * This class defines the methods as abstract that subclasses must implement.
537 * Callers outside of FileBackend and its helper classes, such as FileOp,
538 * should only call functions that are present in FileBackendBase.
540 * The FileBackendBase operations are implemented using primitive functions
541 * such as storeInternal(), copyInternal(), deleteInternal() and the like.
542 * This class is also responsible for path resolution and sanitization.
544 * @ingroup FileBackend
547 abstract class FileBackend
extends FileBackendBase
{
549 protected $cache = array(); // (storage path => key => value)
550 protected $maxCacheSize = 75; // integer; max paths with entries
552 protected $shardViaHashLevels = array(); // (container name => integer)
555 * Create a file in the backend with the given contents.
556 * Do not call this function from places outside FileBackend and FileOp.
559 * content : the raw file contents
560 * dst : destination storage path
561 * overwriteDest : overwrite any file that exists at the destination
563 * @param $params Array
566 final public function createInternal( array $params ) {
567 $status = $this->doCreateInternal( $params );
568 $this->clearCache( array( $params['dst'] ) );
573 * @see FileBackend::createInternal()
575 abstract protected function doCreateInternal( array $params );
578 * Store a file into the backend from a file on disk.
579 * Do not call this function from places outside FileBackend and FileOp.
582 * src : source path on disk
583 * dst : destination storage path
584 * overwriteDest : overwrite any file that exists at the destination
586 * @param $params Array
589 final public function storeInternal( array $params ) {
590 $status = $this->doStoreInternal( $params );
591 $this->clearCache( array( $params['dst'] ) );
596 * @see FileBackend::storeInternal()
598 abstract protected function doStoreInternal( array $params );
601 * Copy a file from one storage path to another in the backend.
602 * Do not call this function from places outside FileBackend and FileOp.
605 * src : source storage path
606 * dst : destination storage path
607 * overwriteDest : overwrite any file that exists at the destination
609 * @param $params Array
612 final public function copyInternal( array $params ) {
613 $status = $this->doCopyInternal( $params );
614 $this->clearCache( array( $params['dst'] ) );
619 * @see FileBackend::copyInternal()
621 abstract protected function doCopyInternal( array $params );
624 * Delete a file at the storage path.
625 * Do not call this function from places outside FileBackend and FileOp.
628 * src : source storage path
629 * ignoreMissingSource : do nothing if the source file does not exist
631 * @param $params Array
634 final public function deleteInternal( array $params ) {
635 $status = $this->doDeleteInternal( $params );
636 $this->clearCache( array( $params['src'] ) );
641 * @see FileBackend::deleteInternal()
643 abstract protected function doDeleteInternal( array $params );
646 * Move a file from one storage path to another in the backend.
647 * Do not call this function from places outside FileBackend and FileOp.
650 * src : source storage path
651 * dst : destination storage path
652 * overwriteDest : overwrite any file that exists at the destination
654 * @param $params Array
657 final public function moveInternal( array $params ) {
658 $status = $this->doMoveInternal( $params );
659 $this->clearCache( array( $params['src'], $params['dst'] ) );
664 * @see FileBackend::moveInternal()
666 protected function doMoveInternal( array $params ) {
667 // Copy source to dest
668 $status = $this->copyInternal( $params );
669 if ( !$status->isOK() ) {
672 // Delete source (only fails due to races or medium going down)
673 $status->merge( $this->deleteInternal( array( 'src' => $params['src'] ) ) );
674 $status->setResult( true, $status->value
); // ignore delete() errors
679 * @see FileBackendBase::concatenate()
681 final public function concatenate( array $params ) {
682 $status = Status
::newGood();
684 // Try to lock the source files for the scope of this function
685 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager
::LOCK_UW
, $status );
686 if ( !$status->isOK() ) {
687 return $status; // abort
690 // Actually do the concatenation
691 $status->merge( $this->doConcatenate( $params ) );
697 * @see FileBackend::concatenate()
699 protected function doConcatenate( array $params ) {
700 $status = Status
::newGood();
701 $tmpPath = $params['dst']; // convenience
703 // Check that the specified temp file is valid...
704 wfSuppressWarnings();
705 $ok = ( is_file( $tmpPath ) && !filesize( $tmpPath ) );
707 if ( !$ok ) { // not present or not empty
708 $status->fatal( 'backend-fail-opentemp', $tmpPath );
712 // Build up the temp file using the source chunks (in order)...
713 $tmpHandle = fopen( $tmpPath, 'a' );
714 if ( $tmpHandle === false ) {
715 $status->fatal( 'backend-fail-opentemp', $tmpPath );
718 foreach ( $params['srcs'] as $virtualSource ) {
719 // Get a local FS version of the chunk
720 $tmpFile = $this->getLocalReference( array( 'src' => $virtualSource ) );
722 $status->fatal( 'backend-fail-read', $virtualSource );
725 // Get a handle to the local FS version
726 $sourceHandle = fopen( $tmpFile->getPath(), 'r' );
727 if ( $sourceHandle === false ) {
728 fclose( $tmpHandle );
729 $status->fatal( 'backend-fail-read', $virtualSource );
732 // Append chunk to file (pass chunk size to avoid magic quotes)
733 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
734 fclose( $sourceHandle );
735 fclose( $tmpHandle );
736 $status->fatal( 'backend-fail-writetemp', $tmpPath );
739 fclose( $sourceHandle );
741 if ( !fclose( $tmpHandle ) ) {
742 $status->fatal( 'backend-fail-closetemp', $tmpPath );
750 * @see FileBackendBase::prepare()
752 final public function prepare( array $params ) {
753 $status = Status
::newGood();
754 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
755 if ( $dir === null ) {
756 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
757 return $status; // invalid storage path
759 if ( $shard !== null ) { // confined to a single container/shard
760 $status->merge( $this->doPrepare( $fullCont, $dir, $params ) );
761 } else { // directory is on several shards
762 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
763 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
764 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
765 $status->merge( $this->doPrepare( "{$fullCont}{$suffix}", $dir, $params ) );
772 * @see FileBackend::prepare()
774 protected function doPrepare( $container, $dir, array $params ) {
775 return Status
::newGood();
779 * @see FileBackendBase::secure()
781 final public function secure( array $params ) {
782 $status = Status
::newGood();
783 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
784 if ( $dir === null ) {
785 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
786 return $status; // invalid storage path
788 if ( $shard !== null ) { // confined to a single container/shard
789 $status->merge( $this->doSecure( $fullCont, $dir, $params ) );
790 } else { // directory is on several shards
791 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
792 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
793 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
794 $status->merge( $this->doSecure( "{$fullCont}{$suffix}", $dir, $params ) );
801 * @see FileBackend::secure()
803 protected function doSecure( $container, $dir, array $params ) {
804 return Status
::newGood();
808 * @see FileBackendBase::clean()
810 final public function clean( array $params ) {
811 $status = Status
::newGood();
812 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
813 if ( $dir === null ) {
814 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
815 return $status; // invalid storage path
817 if ( $shard !== null ) { // confined to a single container/shard
818 $status->merge( $this->doClean( $fullCont, $dir, $params ) );
819 } else { // directory is on several shards
820 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
821 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
822 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
823 $status->merge( $this->doClean( "{$fullCont}{$suffix}", $dir, $params ) );
830 * @see FileBackend::clean()
832 protected function doClean( $container, $dir, array $params ) {
833 return Status
::newGood();
837 * @see FileBackendBase::fileExists()
839 final public function fileExists( array $params ) {
840 return (bool)$this->getFileStat( $params );
844 * @see FileBackendBase::getFileTimestamp()
846 final public function getFileTimestamp( array $params ) {
847 $stat = $this->getFileStat( $params );
849 return $stat['mtime'];
856 * @see FileBackendBase::getFileSize()
858 final public function getFileSize( array $params ) {
859 $stat = $this->getFileStat( $params );
861 return $stat['size'];
868 * @see FileBackendBase::getFileStat()
870 final public function getFileStat( array $params ) {
871 $path = $params['src'];
872 if ( isset( $this->cache
[$path]['stat'] ) ) {
873 return $this->cache
[$path]['stat'];
875 $stat = $this->doGetFileStat( $params );
876 if ( is_array( $stat ) ) { // don't cache negatives
877 $this->trimCache(); // limit memory
878 $this->cache
[$path]['stat'] = $stat;
884 * @see FileBackend::getFileStat()
886 abstract protected function doGetFileStat( array $params );
889 * @see FileBackendBase::getFileContents()
891 public function getFileContents( array $params ) {
892 $tmpFile = $this->getLocalReference( $params );
896 wfSuppressWarnings();
897 $data = file_get_contents( $tmpFile->getPath() );
903 * @see FileBackendBase::getFileSha1Base36()
905 final public function getFileSha1Base36( array $params ) {
906 $path = $params['src'];
907 if ( isset( $this->cache
[$path]['sha1'] ) ) {
908 return $this->cache
[$path]['sha1'];
910 $hash = $this->doGetFileSha1Base36( $params );
911 if ( $hash ) { // don't cache negatives
912 $this->trimCache(); // limit memory
913 $this->cache
[$path]['sha1'] = $hash;
919 * @see FileBackend::getFileSha1Base36()
921 protected function doGetFileSha1Base36( array $params ) {
922 $fsFile = $this->getLocalReference( $params );
926 return $fsFile->getSha1Base36();
931 * @see FileBackendBase::getFileProps()
933 public function getFileProps( array $params ) {
934 $fsFile = $this->getLocalReference( $params );
936 return FSFile
::placeholderProps();
938 return $fsFile->getProps();
943 * @see FileBackendBase::getLocalReference()
945 public function getLocalReference( array $params ) {
946 $path = $params['src'];
947 if ( isset( $this->cache
[$path]['localRef'] ) ) {
948 return $this->cache
[$path]['localRef'];
950 $tmpFile = $this->getLocalCopy( $params );
951 if ( $tmpFile ) { // don't cache negatives
952 $this->trimCache(); // limit memory
953 $this->cache
[$path]['localRef'] = $tmpFile;
959 * @see FileBackendBase::streamFile()
961 final public function streamFile( array $params ) {
962 $status = Status
::newGood();
964 $info = $this->getFileStat( $params );
965 if ( !$info ) { // let StreamFile handle the 404
966 $status->fatal( 'backend-fail-notexists', $params['src'] );
969 // Set output buffer and HTTP headers for stream
970 $extraHeaders = $params['headers'] ?
$params['headers'] : array();
971 $res = StreamFile
::prepareForStream( $params['src'], $info, $extraHeaders );
972 if ( $res == StreamFile
::NOT_MODIFIED
) {
973 // do nothing; client cache is up to date
974 } elseif ( $res == StreamFile
::READY_STREAM
) {
975 $status = $this->doStreamFile( $params );
977 $status->fatal( 'backend-fail-stream', $params['src'] );
984 * @see FileBackend::streamFile()
986 protected function doStreamFile( array $params ) {
987 $status = Status
::newGood();
989 $fsFile = $this->getLocalReference( $params );
991 $status->fatal( 'backend-fail-stream', $params['src'] );
992 } elseif ( !readfile( $fsFile->getPath() ) ) {
993 $status->fatal( 'backend-fail-stream', $params['src'] );
1000 * @see FileBackendBase::getFileList()
1002 final public function getFileList( array $params ) {
1003 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
1004 if ( $dir === null ) { // invalid storage path
1007 if ( $shard !== null ) {
1008 // File listing is confined to a single container/shard
1009 return $this->getFileListInternal( $fullCont, $dir, $params );
1011 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
1012 // File listing spans multiple containers/shards
1013 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
1014 return new ContainerShardListIterator( $this,
1015 $fullCont, $this->getContainerSuffixes( $shortCont ), $params );
1020 * Do not call this function from places outside FileBackend and ContainerFileListIterator
1022 * @param $container string Resolved container name
1023 * @param $dir string Resolved path relative to container
1024 * @param $params Array
1025 * @see FileBackend::getFileList()
1027 abstract public function getFileListInternal( $container, $dir, array $params );
1030 * Get the list of supported operations and their corresponding FileOp classes.
1034 protected function supportedOperations() {
1036 'store' => 'StoreFileOp',
1037 'copy' => 'CopyFileOp',
1038 'move' => 'MoveFileOp',
1039 'delete' => 'DeleteFileOp',
1040 'create' => 'CreateFileOp',
1041 'null' => 'NullFileOp'
1046 * Return a list of FileOp objects from a list of operations.
1047 * Do not call this function from places outside FileBackend.
1049 * The result must have the same number of items as the input.
1050 * An exception is thrown if an unsupported operation is requested.
1052 * @param $ops Array Same format as doOperations()
1053 * @return Array List of FileOp objects
1054 * @throws MWException
1056 final public function getOperations( array $ops ) {
1057 $supportedOps = $this->supportedOperations();
1059 $performOps = array(); // array of FileOp objects
1060 // Build up ordered array of FileOps...
1061 foreach ( $ops as $operation ) {
1062 $opName = $operation['op'];
1063 if ( isset( $supportedOps[$opName] ) ) {
1064 $class = $supportedOps[$opName];
1065 // Get params for this operation
1066 $params = $operation;
1067 // Append the FileOp class
1068 $performOps[] = new $class( $this, $params );
1070 throw new MWException( "Operation `$opName` is not supported." );
1078 * @see FileBackendBase::doOperationsInternal()
1080 protected function doOperationsInternal( array $ops, array $opts ) {
1081 $status = Status
::newGood();
1083 // Build up a list of FileOps...
1084 $performOps = $this->getOperations( $ops );
1086 // Acquire any locks as needed...
1087 if ( empty( $opts['nonLocking'] ) ) {
1088 // Build up a list of files to lock...
1089 $filesLockEx = $filesLockSh = array();
1090 foreach ( $performOps as $fileOp ) {
1091 $filesLockSh = array_merge( $filesLockSh, $fileOp->storagePathsRead() );
1092 $filesLockEx = array_merge( $filesLockEx, $fileOp->storagePathsChanged() );
1094 // Optimization: if doing an EX lock anyway, don't also set an SH one
1095 $filesLockSh = array_diff( $filesLockSh, $filesLockEx );
1096 // Try to lock those files for the scope of this function...
1097 $scopeLockS = $this->getScopedFileLocks( $filesLockSh, LockManager
::LOCK_UW
, $status );
1098 $scopeLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
1099 if ( !$status->isOK() ) {
1100 return $status; // abort
1104 // Clear any cache entries (after locks acquired)
1105 $this->clearCache();
1107 // Actually attempt the operation batch...
1108 $subStatus = FileOp
::attemptBatch( $performOps, $opts );
1110 // Merge errors into status fields
1111 $status->merge( $subStatus );
1112 $status->success
= $subStatus->success
; // not done in merge()
1118 * @see FileBackendBase::clearCache()
1120 final public function clearCache( array $paths = null ) {
1121 if ( $paths === null ) {
1122 $this->cache
= array();
1124 foreach ( $paths as $path ) {
1125 unset( $this->cache
[$path] );
1131 * Prune the cache if it is too big to add an item
1135 protected function trimCache() {
1136 if ( count( $this->cache
) >= $this->maxCacheSize
) {
1137 reset( $this->cache
);
1138 $key = key( $this->cache
);
1139 unset( $this->cache
[$key] );
1144 * Check if a given path is a mwstore:// path.
1145 * This does not do any actual validation or existence checks.
1147 * @param $path string
1150 final public static function isStoragePath( $path ) {
1151 return ( strpos( $path, 'mwstore://' ) === 0 );
1155 * Split a storage path (e.g. "mwstore://backend/container/path/to/object")
1156 * into a backend name, a container name, and a relative object path.
1158 * @param $storagePath string
1159 * @return Array (backend, container, rel object) or (null, null, null)
1161 final public static function splitStoragePath( $storagePath ) {
1162 if ( self
::isStoragePath( $storagePath ) ) {
1163 // Note: strlen( 'mwstore://' ) = 10
1164 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1165 if ( count( $parts ) == 3 ) {
1166 return $parts; // e.g. "backend/container/path"
1167 } elseif ( count( $parts ) == 2 ) {
1168 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
1171 return array( null, null, null );
1175 * Check if a container name is valid.
1176 * This checks for for length and illegal characters.
1178 * @param $container string
1181 final protected static function isValidContainerName( $container ) {
1182 // This accounts for Swift and S3 restrictions while leaving room
1183 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1184 // Note that matching strings URL encode to the same string;
1185 // in Swift, the length resriction is *after* URL encoding.
1186 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1190 * Validate and normalize a relative storage path.
1191 * Null is returned if the path involves directory traversal.
1192 * Traversal is insecure for FS backends and broken for others.
1194 * @param $path string
1195 * @return string|null
1197 final protected static function normalizeStoragePath( $path ) {
1198 // Normalize directory separators
1199 $path = strtr( $path, '\\', '/' );
1200 // Use the same traversal protection as Title::secureAndSplit()
1201 if ( strpos( $path, '.' ) !== false ) {
1205 strpos( $path, './' ) === 0 ||
1206 strpos( $path, '../' ) === 0 ||
1207 strpos( $path, '/./' ) !== false ||
1208 strpos( $path, '/../' ) !== false
1217 * Splits a storage path into an internal container name,
1218 * an internal relative file name, and a container shard suffix.
1219 * Any shard suffix is already appended to the internal container name.
1220 * This also checks that the storage path is valid and within this backend.
1222 * If the container is sharded but a suffix could not be determined,
1223 * this means that the path can only refer to a directory and can only
1224 * be scanned by looking in all the container shards.
1226 * @param $storagePath string
1227 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1229 final protected function resolveStoragePath( $storagePath ) {
1230 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1231 if ( $backend === $this->name
) { // must be for this backend
1232 $relPath = self
::normalizeStoragePath( $relPath );
1233 if ( $relPath !== null ) {
1234 // Get shard for the normalized path if this container is sharded
1235 $cShard = $this->getContainerShard( $container, $relPath );
1236 // Validate and sanitize the relative path (backend-specific)
1237 $relPath = $this->resolveContainerPath( $container, $relPath );
1238 if ( $relPath !== null ) {
1239 // Prepend any wiki ID prefix to the container name
1240 $container = $this->fullContainerName( $container );
1241 if ( self
::isValidContainerName( $container ) ) {
1242 // Validate and sanitize the container name (backend-specific)
1243 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1244 if ( $container !== null ) {
1245 return array( $container, $relPath, $cShard );
1251 return array( null, null, null );
1255 * Like resolveStoragePath() except null values are returned if
1256 * the container is sharded and the shard could not be determined.
1258 * @see FileBackend::resolveStoragePath()
1260 * @param $storagePath string
1261 * @return Array (container, path) or (null, null) if invalid
1263 final protected function resolveStoragePathReal( $storagePath ) {
1264 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1265 if ( $cShard !== null ) {
1266 return array( $container, $relPath );
1268 return array( null, null );
1272 * Get the container name shard suffix for a given path.
1273 * Any empty suffix means the container is not sharded.
1275 * @param $container string Container name
1276 * @param $relStoragePath string Storage path relative to the container
1277 * @return string|null Returns null if shard could not be determined
1279 final protected function getContainerShard( $container, $relPath ) {
1280 $hashLevels = $this->getContainerHashLevels( $container );
1281 if ( $hashLevels === 1 ) { // 16 shards per container
1282 $hashDirRegex = '(?P<shard>[0-9a-f])';
1283 } elseif ( $hashLevels === 2 ) { // 256 shards per container
1284 $hashDirRegex = '[0-9a-f]/(?P<shard>[0-9a-f]{2})';
1286 return ''; // no sharding
1288 // Allow certain directories to be above the hash dirs so as
1289 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1290 // They must be 2+ chars to avoid any hash directory ambiguity.
1291 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1292 return '.' . str_pad( $m['shard'], $hashLevels, '0', STR_PAD_LEFT
);
1294 return null; // failed to match
1298 * Get the number of hash levels for a container.
1299 * If greater than 0, then all file storage paths within
1300 * the container are required to be hashed accordingly.
1302 * @param $container string
1305 final protected function getContainerHashLevels( $container ) {
1306 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1307 $hashLevels = (int)$this->shardViaHashLevels
[$container];
1308 if ( $hashLevels >= 0 && $hashLevels <= 2 ) {
1312 return 0; // no sharding
1316 * Get a list of full container shard suffixes for a container
1318 * @param $container string
1321 final protected function getContainerSuffixes( $container ) {
1323 $digits = $this->getContainerHashLevels( $container );
1324 if ( $digits > 0 ) {
1325 $numShards = 1 << ( $digits * 4 );
1326 for ( $index = 0; $index < $numShards; $index++
) {
1327 $shards[] = '.' . str_pad( dechex( $index ), $digits, '0', STR_PAD_LEFT
);
1334 * Get the full container name, including the wiki ID prefix
1336 * @param $container string
1339 final protected function fullContainerName( $container ) {
1340 if ( $this->wikiId
!= '' ) {
1341 return "{$this->wikiId}-$container";
1348 * Resolve a container name, checking if it's allowed by the backend.
1349 * This is intended for internal use, such as encoding illegal chars.
1350 * Subclasses can override this to be more restrictive.
1352 * @param $container string
1353 * @return string|null
1355 protected function resolveContainerName( $container ) {
1360 * Resolve a relative storage path, checking if it's allowed by the backend.
1361 * This is intended for internal use, such as encoding illegal chars or perhaps
1362 * getting absolute paths (e.g. FS based backends). Note that the relative path
1363 * may be the empty string (e.g. the path is simply to the container).
1365 * @param $container string Container name
1366 * @param $relStoragePath string Storage path relative to the container
1367 * @return string|null Path or null if not valid
1369 protected function resolveContainerPath( $container, $relStoragePath ) {
1370 return $relStoragePath;
1374 * Get the final extension from a storage or FS path
1376 * @param $path string
1379 final public static function extensionFromPath( $path ) {
1380 $i = strrpos( $path, '.' );
1381 return strtolower( $i ?
substr( $path, $i +
1 ) : '' );
1386 * FileBackend helper function to handle file listings that span container shards.
1387 * Do not use this class from places outside of FileBackend.
1389 * @ingroup FileBackend
1391 class ContainerShardListIterator
implements Iterator
{
1392 /* @var FileBackend */
1397 protected $shardSuffixes;
1398 protected $container; // string
1399 protected $directory; // string
1401 /* @var Traversable */
1403 protected $curShard = 0; // integer
1404 protected $pos = 0; // integer
1407 * @param $backend FileBackend
1408 * @param $container string Full storage container name
1409 * @param $dir string Storage directory relative to container
1410 * @param $suffixes Array List of container shard suffixes
1411 * @param $params Array
1413 public function __construct(
1414 FileBackend
$backend, $container, $dir, array $suffixes, array $params
1416 $this->backend
= $backend;
1417 $this->container
= $container;
1418 $this->directory
= $dir;
1419 $this->shardSuffixes
= $suffixes;
1420 $this->params
= $params;
1423 public function current() {
1424 if ( is_array( $this->iter
) ) {
1425 return current( $this->iter
);
1427 return $this->iter
->current();
1431 public function key() {
1435 public function next() {
1437 if ( is_array( $this->iter
) ) {
1438 next( $this->iter
);
1440 $this->iter
->next();
1442 // Find the next non-empty shard if no elements are left
1443 $this->nextShardIteratorIfNotValid();
1447 * If the iterator for this container shard is out of items,
1448 * then move on to the next container that has items.
1449 * If there are none, then it advances to the last container.
1451 protected function nextShardIteratorIfNotValid() {
1452 while ( !$this->valid() ) {
1453 if ( ++
$this->curShard
>= count( $this->shardSuffixes
) ) {
1454 break; // no more container shards
1456 $this->setIteratorFromCurrentShard();
1460 protected function setIteratorFromCurrentShard() {
1461 $suffix = $this->shardSuffixes
[$this->curShard
];
1462 $this->iter
= $this->backend
->getFileListInternal(
1463 "{$this->container}{$suffix}", $this->directory
, $this->params
);
1466 public function rewind() {
1468 $this->curShard
= 0;
1469 $this->setIteratorFromCurrentShard();
1470 // Find the next non-empty shard if this one has no elements
1471 $this->nextShardIteratorIfNotValid();
1474 public function valid() {
1475 if ( $this->iter
== null ) {
1476 return false; // some failure?
1477 } elseif ( is_array( $this->iter
) ) {
1478 return ( current( $this->iter
) !== false ); // no paths can have this value
1480 return $this->iter
->valid();