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; // string; unique backend name
34 protected $wikiId; // string; unique wiki name
35 protected $readOnly; // string; read-only explanation message
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->lockManager
= LockManagerGroup
::singleton()->get( $config['lockManager'] );
59 $this->readOnly
= isset( $config['readOnly'] )
60 ?
(string)$config['readOnly']
65 * Get the unique backend name.
66 * We may have multiple different backends of the same type.
67 * For example, we can have two Swift backends using different proxies.
71 final public function getName() {
76 * This is the main entry point into the backend for write operations.
77 * Callers supply an ordered list of operations to perform as a transaction.
78 * Files will be locked, the stat cache cleared, and then the operations attempted.
79 * If any serious errors occur, all attempted operations will be rolled back.
81 * $ops is an array of arrays. The outer array holds a list of operations.
82 * Each inner array is a set of key value pairs that specify an operation.
84 * Supported operations and their parameters:
85 * a) Create a new file in storage with the contents of a string
88 * 'dst' => <storage path>,
89 * 'content' => <string of new file contents>,
90 * 'overwrite' => <boolean>,
91 * 'overwriteSame' => <boolean>
93 * b) Copy a file system file into storage
96 * 'src' => <file system path>,
97 * 'dst' => <storage path>,
98 * 'overwrite' => <boolean>,
99 * 'overwriteSame' => <boolean>
101 * c) Copy a file within storage
104 * 'src' => <storage path>,
105 * 'dst' => <storage path>,
106 * 'overwrite' => <boolean>,
107 * 'overwriteSame' => <boolean>
109 * d) Move a file within storage
112 * 'src' => <storage path>,
113 * 'dst' => <storage path>,
114 * 'overwrite' => <boolean>,
115 * 'overwriteSame' => <boolean>
117 * e) Delete a file within storage
120 * 'src' => <storage path>,
121 * 'ignoreMissingSource' => <boolean>
123 * f) Do nothing (no-op)
128 * Boolean flags for operations (operation-specific):
129 * 'ignoreMissingSource' : The operation will simply succeed and do
130 * nothing if the source file does not exist.
131 * 'overwrite' : Any destination file will be overwritten.
132 * 'overwriteSame' : An error will not be given if a file already
133 * exists at the destination that has the same
134 * contents as the new contents to be written there.
136 * $opts is an associative of boolean flags, including:
137 * 'force' : Errors that would normally cause a rollback do not.
138 * The remaining operations are still attempted if any fail.
139 * 'nonLocking' : No locks are acquired for the operations.
140 * This can increase performance for non-critical writes.
141 * This has no effect unless the 'force' flag is set.
142 * 'allowStale' : Don't require the latest available data.
143 * This can increase performance for non-critical writes.
144 * This has no effect unless the 'force' flag is set.
146 * Remarks on locking:
147 * File system paths given to operations should refer to files that are
148 * already locked or otherwise safe from modification from other processes.
149 * Normally these files will be new temp files, which should be adequate.
152 * This returns a Status, which contains all warnings and fatals that occured
153 * during the operation. The 'failCount', 'successCount', and 'success' members
154 * will reflect each operation attempted. The status will be "OK" unless any
155 * of the operations failed and the 'force' parameter was not set.
157 * @param $ops Array List of operations to execute in order
158 * @param $opts Array Batch operation options
161 final public function doOperations( array $ops, array $opts = array() ) {
162 if ( $this->readOnly
!= '' ) {
163 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
165 if ( empty( $opts['force'] ) ) { // sanity
166 unset( $opts['nonLocking'] );
167 unset( $opts['allowStale'] );
169 return $this->doOperationsInternal( $ops, $opts );
173 * @see FileBackendBase::doOperations()
175 abstract protected function doOperationsInternal( array $ops, array $opts );
178 * Same as doOperations() except it takes a single operation.
179 * If you are doing a batch of operations that should either
180 * all succeed or all fail, then use that function instead.
182 * @see FileBackendBase::doOperations()
184 * @param $op Array Operation
185 * @param $opts Array Operation options
188 final public function doOperation( array $op, array $opts = array() ) {
189 return $this->doOperations( array( $op ), $opts );
193 * Performs a single create operation.
194 * This sets $params['op'] to 'create' and passes it to doOperation().
196 * @see FileBackendBase::doOperation()
198 * @param $params Array Operation parameters
199 * @param $opts Array Operation options
202 final public function create( array $params, array $opts = array() ) {
203 $params['op'] = 'create';
204 return $this->doOperation( $params, $opts );
208 * Performs a single store operation.
209 * This sets $params['op'] to 'store' and passes it to doOperation().
211 * @see FileBackendBase::doOperation()
213 * @param $params Array Operation parameters
214 * @param $opts Array Operation options
217 final public function store( array $params, array $opts = array() ) {
218 $params['op'] = 'store';
219 return $this->doOperation( $params, $opts );
223 * Performs a single copy operation.
224 * This sets $params['op'] to 'copy' and passes it to doOperation().
226 * @see FileBackendBase::doOperation()
228 * @param $params Array Operation parameters
229 * @param $opts Array Operation options
232 final public function copy( array $params, array $opts = array() ) {
233 $params['op'] = 'copy';
234 return $this->doOperation( $params, $opts );
238 * Performs a single move operation.
239 * This sets $params['op'] to 'move' and passes it to doOperation().
241 * @see FileBackendBase::doOperation()
243 * @param $params Array Operation parameters
244 * @param $opts Array Operation options
247 final public function move( array $params, array $opts = array() ) {
248 $params['op'] = 'move';
249 return $this->doOperation( $params, $opts );
253 * Performs a single delete operation.
254 * This sets $params['op'] to 'delete' and passes it to doOperation().
256 * @see FileBackendBase::doOperation()
258 * @param $params Array Operation parameters
259 * @param $opts Array Operation options
262 final public function delete( array $params, array $opts = array() ) {
263 $params['op'] = 'delete';
264 return $this->doOperation( $params, $opts );
268 * Concatenate a list of storage files into a single file system file.
269 * The target path should refer to a file that is already locked or
270 * otherwise safe from modification from other processes. Normally,
271 * the file will be a new temp file, which should be adequate.
273 * srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
274 * dst : file system path to 0-byte temp file
276 * @param $params Array Operation parameters
279 abstract public function concatenate( array $params );
282 * Prepare a storage directory for usage.
283 * This will create any required containers and parent directories.
284 * Backends using key/value stores only need to create the container.
287 * dir : storage directory
289 * @param $params Array
292 final public function prepare( array $params ) {
293 if ( $this->readOnly
!= '' ) {
294 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
296 return $this->doPrepare( $params );
300 * @see FileBackendBase::prepare()
302 abstract protected function doPrepare( array $params );
305 * Take measures to block web access to a storage directory and
306 * the container it belongs to. FS backends might add .htaccess
307 * files whereas key/value store backends might restrict container
308 * access to the auth user that represents end-users in web request.
309 * This is not guaranteed to actually do anything.
312 * dir : storage directory
313 * noAccess : try to deny file access
314 * noListing : try to deny file listing
316 * @param $params Array
319 final public function secure( array $params ) {
320 if ( $this->readOnly
!= '' ) {
321 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
323 $status = $this->doPrepare( $params ); // dir must exist to restrict it
324 if ( $status->isOK() ) {
325 $status->merge( $this->doSecure( $params ) );
331 * @see FileBackendBase::secure()
333 abstract protected function doSecure( array $params );
336 * Delete a storage directory if it is empty.
337 * Backends using key/value stores may do nothing unless the directory
338 * is that of an empty container, in which case it should be deleted.
341 * dir : storage directory
343 * @param $params Array
346 final public function clean( array $params ) {
347 if ( $this->readOnly
!= '' ) {
348 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
350 return $this->doClean( $params );
354 * @see FileBackendBase::clean()
356 abstract protected function doClean( array $params );
359 * Check if a file exists at a storage path in the backend.
360 * This returns false if only a directory exists at the path.
363 * src : source storage path
364 * latest : use the latest available data
366 * @param $params Array
367 * @return bool|null Returns null on failure
369 abstract public function fileExists( array $params );
372 * Get the last-modified timestamp of the file at a storage path.
375 * src : source storage path
376 * latest : use the latest available data
378 * @param $params Array
379 * @return string|false TS_MW timestamp or false on failure
381 abstract public function getFileTimestamp( array $params );
384 * Get the contents of a file at a storage path in the backend.
385 * This should be avoided for potentially large files.
388 * src : source storage path
389 * latest : use the latest available data
391 * @param $params Array
392 * @return string|false Returns false on failure
394 abstract public function getFileContents( array $params );
397 * Get the size (bytes) of a file at a storage path in the backend.
400 * src : source storage path
401 * latest : use the latest available data
403 * @param $params Array
404 * @return integer|false Returns false on failure
406 abstract public function getFileSize( array $params );
409 * Get quick information about a file at a storage path in the backend.
410 * If the file does not exist, then this returns false.
411 * Otherwise, the result is an associative array that includes:
412 * mtime : the last-modified timestamp (TS_MW)
413 * size : the file size (bytes)
414 * Additional values may be included for internal use only.
417 * src : source storage path
418 * latest : use the latest available data
420 * @param $params Array
421 * @return Array|false|null Returns null on failure
423 abstract public function getFileStat( array $params );
426 * Get a SHA-1 hash of the file at a storage path in the backend.
429 * src : source storage path
430 * latest : use the latest available data
432 * @param $params Array
433 * @return string|false Hash string or false on failure
435 abstract public function getFileSha1Base36( array $params );
438 * Get the properties of the file at a storage path in the backend.
439 * Returns FSFile::placeholderProps() on failure.
442 * src : source storage path
443 * latest : use the latest available data
445 * @param $params Array
448 abstract public function getFileProps( array $params );
451 * Stream the file at a storage path in the backend.
452 * If the file does not exists, a 404 error will be given.
453 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
454 * must be sent if streaming began, while none should be sent otherwise.
455 * Implementations should flush the output buffer before sending data.
458 * src : source storage path
459 * headers : additional HTTP headers to send on success
460 * latest : use the latest available data
462 * @param $params Array
465 abstract public function streamFile( array $params );
468 * Returns a file system file, identical to the file at a storage path.
469 * The file returned is either:
470 * a) A local copy of the file at a storage path in the backend.
471 * The temporary copy will have the same extension as the source.
472 * b) An original of the file at a storage path in the backend.
473 * Temporary files may be purged when the file object falls out of scope.
475 * Write operations should *never* be done on this file as some backends
476 * may do internal tracking or may be instances of FileBackendMultiWrite.
477 * In that later case, there are copies of the file that must stay in sync.
478 * Additionally, further calls to this function may return the same file.
481 * src : source storage path
482 * latest : use the latest available data
484 * @param $params Array
485 * @return FSFile|null Returns null on failure
487 abstract public function getLocalReference( array $params );
490 * Get a local copy on disk of the file at a storage path in the backend.
491 * The temporary copy will have the same file extension as the source.
492 * Temporary files may be purged when the file object falls out of scope.
495 * src : source storage path
496 * latest : use the latest available data
498 * @param $params Array
499 * @return TempFSFile|null Returns null on failure
501 abstract public function getLocalCopy( array $params );
504 * Get an iterator to list out all stored files under a storage directory.
505 * If the directory is of the form "mwstore://container", then all items in
506 * the container should be listed. If of the form "mwstore://container/dir",
507 * then all items under that container directory should be listed.
508 * Results should be storage paths relative to the given directory.
511 * dir : storage path directory
513 * @return Traversable|Array|null Returns null on failure
515 abstract public function getFileList( array $params );
518 * Invalidate any in-process file existence and property cache.
519 * If $paths is given, then only the cache for those files will be cleared.
521 * @param $paths Array Storage paths (optional)
524 public function clearCache( array $paths = null ) {}
527 * Lock the files at the given storage paths in the backend.
528 * This will either lock all the files or none (on failure).
530 * Callers should consider using getScopedFileLocks() instead.
532 * @param $paths Array Storage paths
533 * @param $type integer LockManager::LOCK_* constant
536 final public function lockFiles( array $paths, $type ) {
537 return $this->lockManager
->lock( $paths, $type );
541 * Unlock the files at the given storage paths in the backend.
543 * @param $paths Array Storage paths
544 * @param $type integer LockManager::LOCK_* constant
547 final public function unlockFiles( array $paths, $type ) {
548 return $this->lockManager
->unlock( $paths, $type );
552 * Lock the files at the given storage paths in the backend.
553 * This will either lock all the files or none (on failure).
554 * On failure, the status object will be updated with errors.
556 * Once the return value goes out scope, the locks will be released and
557 * the status updated. Unlock fatals will not change the status "OK" value.
559 * @param $paths Array Storage paths
560 * @param $type integer LockManager::LOCK_* constant
561 * @param $status Status Status to update on lock/unlock
562 * @return ScopedLock|null Returns null on failure
564 final public function getScopedFileLocks( array $paths, $type, Status
$status ) {
565 return ScopedLock
::factory( $this->lockManager
, $paths, $type, $status );
569 * Check if a given path is a "mwstore://" path.
570 * This does not do any further validation or any existence checks.
572 * @param $path string
575 final public static function isStoragePath( $path ) {
576 return ( strpos( $path, 'mwstore://' ) === 0 );
580 * Split a storage path into a backend name, a container name,
581 * and a relative file path. The relative path may be the empty string.
582 * This does not do any path normalization or traversal checks.
584 * @param $storagePath string
585 * @return Array (backend, container, rel object) or (null, null, null)
587 final public static function splitStoragePath( $storagePath ) {
588 if ( self
::isStoragePath( $storagePath ) ) {
589 // Remove the "mwstore://" prefix and split the path
590 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
591 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
592 if ( count( $parts ) == 3 ) {
593 return $parts; // e.g. "backend/container/path"
595 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
599 return array( null, null, null );
603 * Normalize a storage path by cleaning up directory separators.
604 * Returns null if the path is not of the format of a valid storage path.
606 * @param $storagePath string
607 * @return string|null
609 final public static function normalizeStoragePath( $storagePath ) {
610 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
611 if ( $relPath !== null ) { // must be for this backend
612 $relPath = self
::normalizeContainerPath( $relPath );
613 if ( $relPath !== null ) {
614 return ( $relPath != '' )
615 ?
"mwstore://{$backend}/{$container}/{$relPath}"
616 : "mwstore://{$backend}/{$container}";
623 * Validate and normalize a relative storage path.
624 * Null is returned if the path involves directory traversal.
625 * Traversal is insecure for FS backends and broken for others.
627 * @param $path string Storage path relative to a container
628 * @return string|null
630 final protected static function normalizeContainerPath( $path ) {
631 // Normalize directory separators
632 $path = strtr( $path, '\\', '/' );
633 // Collapse any consecutive directory separators
634 $path = preg_replace( '![/]{2,}!', '/', $path );
635 // Remove any leading directory separator
636 $path = ltrim( $path, '/' );
637 // Use the same traversal protection as Title::secureAndSplit()
638 if ( strpos( $path, '.' ) !== false ) {
642 strpos( $path, './' ) === 0 ||
643 strpos( $path, '../' ) === 0 ||
644 strpos( $path, '/./' ) !== false ||
645 strpos( $path, '/../' ) !== false
654 * Get the parent storage directory of a storage path.
655 * This returns a path like "mwstore://backend/container",
656 * "mwstore://backend/container/...", or null if there is no parent.
658 * @param $storagePath string
659 * @return string|null
661 final public static function parentStoragePath( $storagePath ) {
662 $storagePath = dirname( $storagePath );
663 list( $b, $cont, $rel ) = self
::splitStoragePath( $storagePath );
664 return ( $rel === null ) ?
null : $storagePath;
668 * Get the final extension from a storage or FS path
670 * @param $path string
673 final public static function extensionFromPath( $path ) {
674 $i = strrpos( $path, '.' );
675 return strtolower( $i ?
substr( $path, $i +
1 ) : '' );
680 * Base class for all single-write backends.
681 * This class defines the methods as abstract that subclasses must implement.
682 * Outside callers should *not* use functions with "Internal" in the name.
684 * The FileBackendBase operations are implemented using basic functions
685 * such as storeInternal(), copyInternal(), deleteInternal() and the like.
686 * This class is also responsible for path resolution and sanitization.
688 * @ingroup FileBackend
691 abstract class FileBackend
extends FileBackendBase
{
692 /** @var Array Map of paths to small (RAM/disk) cache items */
693 protected $cache = array(); // (storage path => key => value)
694 protected $maxCacheSize = 100; // integer; max paths with entries
695 /** @var Array Map of paths to large (RAM/disk) cache items */
696 protected $expCache = array(); // (storage path => key => value)
697 protected $maxExpCacheSize = 10; // integer; max paths with entries
700 protected $shardViaHashLevels = array(); // (container name => integer)
702 protected $maxFileSize = 1000000000; // integer bytes (1GB)
705 * Get the maximum allowable file size given backend
706 * medium restrictions and basic performance constraints.
707 * Do not call this function from places outside FileBackend and FileOp.
709 * @return integer Bytes
711 final public function maxFileSizeInternal() {
712 return $this->maxFileSize
;
716 * Check if a file can be created at a given storage path.
717 * FS backends should check if the parent directory exists and the file is writable.
718 * Backends using key/value stores should check if the container exists.
720 * @param $storagePath string
723 abstract public function isPathUsableInternal( $storagePath );
726 * Create a file in the backend with the given contents.
727 * Do not call this function from places outside FileBackend and FileOp.
730 * content : the raw file contents
731 * dst : destination storage path
732 * overwrite : overwrite any file that exists at the destination
734 * @param $params Array
737 final public function createInternal( array $params ) {
738 wfProfileIn( __METHOD__
);
739 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
740 $status = Status
::newFatal( 'backend-fail-create', $params['dst'] );
742 $status = $this->doCreateInternal( $params );
743 $this->clearCache( array( $params['dst'] ) );
745 wfProfileOut( __METHOD__
);
750 * @see FileBackend::createInternal()
752 abstract protected function doCreateInternal( array $params );
755 * Store a file into the backend from a file on disk.
756 * Do not call this function from places outside FileBackend and FileOp.
759 * src : source path on disk
760 * dst : destination storage path
761 * overwrite : overwrite any file that exists at the destination
763 * @param $params Array
766 final public function storeInternal( array $params ) {
767 wfProfileIn( __METHOD__
);
768 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
769 $status = Status
::newFatal( 'backend-fail-store', $params['dst'] );
771 $status = $this->doStoreInternal( $params );
772 $this->clearCache( array( $params['dst'] ) );
774 wfProfileOut( __METHOD__
);
779 * @see FileBackend::storeInternal()
781 abstract protected function doStoreInternal( array $params );
784 * Copy a file from one storage path to another in the backend.
785 * Do not call this function from places outside FileBackend and FileOp.
788 * src : source storage path
789 * dst : destination storage path
790 * overwrite : overwrite any file that exists at the destination
792 * @param $params Array
795 final public function copyInternal( array $params ) {
796 wfProfileIn( __METHOD__
);
797 $status = $this->doCopyInternal( $params );
798 $this->clearCache( array( $params['dst'] ) );
799 wfProfileOut( __METHOD__
);
804 * @see FileBackend::copyInternal()
806 abstract protected function doCopyInternal( array $params );
809 * Delete a file at the storage path.
810 * Do not call this function from places outside FileBackend and FileOp.
813 * src : source storage path
814 * ignoreMissingSource : do nothing if the source file does not exist
816 * @param $params Array
819 final public function deleteInternal( array $params ) {
820 wfProfileIn( __METHOD__
);
821 $status = $this->doDeleteInternal( $params );
822 $this->clearCache( array( $params['src'] ) );
823 wfProfileOut( __METHOD__
);
828 * @see FileBackend::deleteInternal()
830 abstract protected function doDeleteInternal( array $params );
833 * Move a file from one storage path to another in the backend.
834 * Do not call this function from places outside FileBackend and FileOp.
837 * src : source storage path
838 * dst : destination storage path
839 * overwrite : overwrite any file that exists at the destination
841 * @param $params Array
844 final public function moveInternal( array $params ) {
845 wfProfileIn( __METHOD__
);
846 $status = $this->doMoveInternal( $params );
847 $this->clearCache( array( $params['src'], $params['dst'] ) );
848 wfProfileOut( __METHOD__
);
853 * @see FileBackend::moveInternal()
855 protected function doMoveInternal( array $params ) {
856 // Copy source to dest
857 $status = $this->copyInternal( $params );
858 if ( $status->isOK() ) {
859 // Delete source (only fails due to races or medium going down)
860 $status->merge( $this->deleteInternal( array( 'src' => $params['src'] ) ) );
861 $status->setResult( true, $status->value
); // ignore delete() errors
867 * @see FileBackendBase::concatenate()
869 final public function concatenate( array $params ) {
870 wfProfileIn( __METHOD__
);
871 $status = Status
::newGood();
873 // Try to lock the source files for the scope of this function
874 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager
::LOCK_UW
, $status );
875 if ( $status->isOK() ) {
876 // Actually do the concatenation
877 $status->merge( $this->doConcatenate( $params ) );
880 wfProfileOut( __METHOD__
);
885 * @see FileBackend::concatenate()
887 protected function doConcatenate( array $params ) {
888 $status = Status
::newGood();
889 $tmpPath = $params['dst']; // convenience
891 // Check that the specified temp file is valid...
892 wfSuppressWarnings();
893 $ok = ( is_file( $tmpPath ) && !filesize( $tmpPath ) );
895 if ( !$ok ) { // not present or not empty
896 $status->fatal( 'backend-fail-opentemp', $tmpPath );
900 // Build up the temp file using the source chunks (in order)...
901 $tmpHandle = fopen( $tmpPath, 'ab' );
902 if ( $tmpHandle === false ) {
903 $status->fatal( 'backend-fail-opentemp', $tmpPath );
906 foreach ( $params['srcs'] as $virtualSource ) {
907 // Get a local FS version of the chunk
908 $tmpFile = $this->getLocalReference( array( 'src' => $virtualSource ) );
910 $status->fatal( 'backend-fail-read', $virtualSource );
913 // Get a handle to the local FS version
914 $sourceHandle = fopen( $tmpFile->getPath(), 'r' );
915 if ( $sourceHandle === false ) {
916 fclose( $tmpHandle );
917 $status->fatal( 'backend-fail-read', $virtualSource );
920 // Append chunk to file (pass chunk size to avoid magic quotes)
921 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
922 fclose( $sourceHandle );
923 fclose( $tmpHandle );
924 $status->fatal( 'backend-fail-writetemp', $tmpPath );
927 fclose( $sourceHandle );
929 if ( !fclose( $tmpHandle ) ) {
930 $status->fatal( 'backend-fail-closetemp', $tmpPath );
934 clearstatcache(); // temp file changed
940 * @see FileBackendBase::doPrepare()
942 final protected function doPrepare( array $params ) {
943 wfProfileIn( __METHOD__
);
945 $status = Status
::newGood();
946 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
947 if ( $dir === null ) {
948 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
949 wfProfileOut( __METHOD__
);
950 return $status; // invalid storage path
953 if ( $shard !== null ) { // confined to a single container/shard
954 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
955 } else { // directory is on several shards
956 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
957 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
958 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
959 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
963 wfProfileOut( __METHOD__
);
968 * @see FileBackend::doPrepare()
970 protected function doPrepareInternal( $container, $dir, array $params ) {
971 return Status
::newGood();
975 * @see FileBackendBase::doSecure()
977 final protected function doSecure( array $params ) {
978 wfProfileIn( __METHOD__
);
979 $status = Status
::newGood();
981 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
982 if ( $dir === null ) {
983 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
984 wfProfileOut( __METHOD__
);
985 return $status; // invalid storage path
988 if ( $shard !== null ) { // confined to a single container/shard
989 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
990 } else { // directory is on several shards
991 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
992 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
993 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
994 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
998 wfProfileOut( __METHOD__
);
1003 * @see FileBackend::doSecure()
1005 protected function doSecureInternal( $container, $dir, array $params ) {
1006 return Status
::newGood();
1010 * @see FileBackendBase::doClean()
1012 final protected function doClean( array $params ) {
1013 wfProfileIn( __METHOD__
);
1014 $status = Status
::newGood();
1016 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
1017 if ( $dir === null ) {
1018 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
1019 wfProfileOut( __METHOD__
);
1020 return $status; // invalid storage path
1023 // Attempt to lock this directory...
1024 $filesLockEx = array( $params['dir'] );
1025 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
1026 if ( !$status->isOK() ) {
1027 wfProfileOut( __METHOD__
);
1028 return $status; // abort
1031 if ( $shard !== null ) { // confined to a single container/shard
1032 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
1033 } else { // directory is on several shards
1034 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
1035 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
1036 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
1037 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
1041 wfProfileOut( __METHOD__
);
1046 * @see FileBackend::doClean()
1048 protected function doCleanInternal( $container, $dir, array $params ) {
1049 return Status
::newGood();
1053 * @see FileBackendBase::fileExists()
1055 final public function fileExists( array $params ) {
1056 wfProfileIn( __METHOD__
);
1057 $stat = $this->getFileStat( $params );
1058 wfProfileOut( __METHOD__
);
1059 return ( $stat === null ) ?
null : (bool)$stat; // null => failure
1063 * @see FileBackendBase::getFileTimestamp()
1065 final public function getFileTimestamp( array $params ) {
1066 wfProfileIn( __METHOD__
);
1067 $stat = $this->getFileStat( $params );
1068 wfProfileOut( __METHOD__
);
1069 return $stat ?
$stat['mtime'] : false;
1073 * @see FileBackendBase::getFileSize()
1075 final public function getFileSize( array $params ) {
1076 wfProfileIn( __METHOD__
);
1077 $stat = $this->getFileStat( $params );
1078 wfProfileOut( __METHOD__
);
1079 return $stat ?
$stat['size'] : false;
1083 * @see FileBackendBase::getFileStat()
1085 final public function getFileStat( array $params ) {
1086 wfProfileIn( __METHOD__
);
1087 $path = self
::normalizeStoragePath( $params['src'] );
1088 if ( $path === null ) {
1089 return false; // invalid storage path
1091 $latest = !empty( $params['latest'] );
1092 if ( isset( $this->cache
[$path]['stat'] ) ) {
1093 // If we want the latest data, check that this cached
1094 // value was in fact fetched with the latest available data.
1095 if ( !$latest ||
$this->cache
[$path]['stat']['latest'] ) {
1096 wfProfileOut( __METHOD__
);
1097 return $this->cache
[$path]['stat'];
1100 $stat = $this->doGetFileStat( $params );
1101 if ( is_array( $stat ) ) { // don't cache negatives
1102 $this->trimCache(); // limit memory
1103 $this->cache
[$path]['stat'] = $stat;
1104 $this->cache
[$path]['stat']['latest'] = $latest;
1106 wfProfileOut( __METHOD__
);
1111 * @see FileBackend::getFileStat()
1113 abstract protected function doGetFileStat( array $params );
1116 * @see FileBackendBase::getFileContents()
1118 public function getFileContents( array $params ) {
1119 wfProfileIn( __METHOD__
);
1120 $tmpFile = $this->getLocalReference( $params );
1122 wfProfileOut( __METHOD__
);
1125 wfSuppressWarnings();
1126 $data = file_get_contents( $tmpFile->getPath() );
1127 wfRestoreWarnings();
1128 wfProfileOut( __METHOD__
);
1133 * @see FileBackendBase::getFileSha1Base36()
1135 final public function getFileSha1Base36( array $params ) {
1136 wfProfileIn( __METHOD__
);
1137 $path = $params['src'];
1138 if ( isset( $this->cache
[$path]['sha1'] ) ) {
1139 wfProfileOut( __METHOD__
);
1140 return $this->cache
[$path]['sha1'];
1142 $hash = $this->doGetFileSha1Base36( $params );
1143 if ( $hash ) { // don't cache negatives
1144 $this->trimCache(); // limit memory
1145 $this->cache
[$path]['sha1'] = $hash;
1147 wfProfileOut( __METHOD__
);
1152 * @see FileBackend::getFileSha1Base36()
1154 protected function doGetFileSha1Base36( array $params ) {
1155 $fsFile = $this->getLocalReference( $params );
1159 return $fsFile->getSha1Base36();
1164 * @see FileBackendBase::getFileProps()
1166 final public function getFileProps( array $params ) {
1167 wfProfileIn( __METHOD__
);
1168 $fsFile = $this->getLocalReference( $params );
1169 $props = $fsFile ?
$fsFile->getProps() : FSFile
::placeholderProps();
1170 wfProfileOut( __METHOD__
);
1175 * @see FileBackendBase::getLocalReference()
1177 public function getLocalReference( array $params ) {
1178 wfProfileIn( __METHOD__
);
1179 $path = $params['src'];
1180 if ( isset( $this->expCache
[$path]['localRef'] ) ) {
1181 wfProfileOut( __METHOD__
);
1182 return $this->expCache
[$path]['localRef'];
1184 $tmpFile = $this->getLocalCopy( $params );
1185 if ( $tmpFile ) { // don't cache negatives
1186 $this->trimExpCache(); // limit memory
1187 $this->expCache
[$path]['localRef'] = $tmpFile;
1189 wfProfileOut( __METHOD__
);
1194 * @see FileBackendBase::streamFile()
1196 final public function streamFile( array $params ) {
1197 wfProfileIn( __METHOD__
);
1198 $status = Status
::newGood();
1200 $info = $this->getFileStat( $params );
1201 if ( !$info ) { // let StreamFile handle the 404
1202 $status->fatal( 'backend-fail-notexists', $params['src'] );
1205 // Set output buffer and HTTP headers for stream
1206 $extraHeaders = $params['headers'] ?
$params['headers'] : array();
1207 $res = StreamFile
::prepareForStream( $params['src'], $info, $extraHeaders );
1208 if ( $res == StreamFile
::NOT_MODIFIED
) {
1209 // do nothing; client cache is up to date
1210 } elseif ( $res == StreamFile
::READY_STREAM
) {
1211 $status = $this->doStreamFile( $params );
1213 $status->fatal( 'backend-fail-stream', $params['src'] );
1216 wfProfileOut( __METHOD__
);
1221 * @see FileBackend::streamFile()
1223 protected function doStreamFile( array $params ) {
1224 $status = Status
::newGood();
1226 $fsFile = $this->getLocalReference( $params );
1228 $status->fatal( 'backend-fail-stream', $params['src'] );
1229 } elseif ( !readfile( $fsFile->getPath() ) ) {
1230 $status->fatal( 'backend-fail-stream', $params['src'] );
1237 * @see FileBackendBase::getFileList()
1239 final public function getFileList( array $params ) {
1240 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
1241 if ( $dir === null ) { // invalid storage path
1244 if ( $shard !== null ) {
1245 // File listing is confined to a single container/shard
1246 return $this->getFileListInternal( $fullCont, $dir, $params );
1248 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
1249 // File listing spans multiple containers/shards
1250 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
1251 return new FileBackendShardListIterator( $this,
1252 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
1257 * Do not call this function from places outside FileBackend
1259 * @see FileBackend::getFileList()
1261 * @param $container string Resolved container name
1262 * @param $dir string Resolved path relative to container
1263 * @param $params Array
1264 * @return Traversable|Array|null
1266 abstract public function getFileListInternal( $container, $dir, array $params );
1269 * Get the list of supported operations and their corresponding FileOp classes.
1273 protected function supportedOperations() {
1275 'store' => 'StoreFileOp',
1276 'copy' => 'CopyFileOp',
1277 'move' => 'MoveFileOp',
1278 'delete' => 'DeleteFileOp',
1279 'create' => 'CreateFileOp',
1280 'null' => 'NullFileOp'
1285 * Return a list of FileOp objects from a list of operations.
1286 * Do not call this function from places outside FileBackend.
1288 * The result must have the same number of items as the input.
1289 * An exception is thrown if an unsupported operation is requested.
1291 * @param $ops Array Same format as doOperations()
1292 * @return Array List of FileOp objects
1293 * @throws MWException
1295 final public function getOperations( array $ops ) {
1296 $supportedOps = $this->supportedOperations();
1298 $performOps = array(); // array of FileOp objects
1299 // Build up ordered array of FileOps...
1300 foreach ( $ops as $operation ) {
1301 $opName = $operation['op'];
1302 if ( isset( $supportedOps[$opName] ) ) {
1303 $class = $supportedOps[$opName];
1304 // Get params for this operation
1305 $params = $operation;
1306 // Append the FileOp class
1307 $performOps[] = new $class( $this, $params );
1309 throw new MWException( "Operation `$opName` is not supported." );
1317 * @see FileBackendBase::doOperationsInternal()
1319 protected function doOperationsInternal( array $ops, array $opts ) {
1320 wfProfileIn( __METHOD__
);
1321 $status = Status
::newGood();
1323 // Build up a list of FileOps...
1324 $performOps = $this->getOperations( $ops );
1326 // Acquire any locks as needed...
1327 if ( empty( $opts['nonLocking'] ) ) {
1328 // Build up a list of files to lock...
1329 $filesLockEx = $filesLockSh = array();
1330 foreach ( $performOps as $fileOp ) {
1331 $filesLockSh = array_merge( $filesLockSh, $fileOp->storagePathsRead() );
1332 $filesLockEx = array_merge( $filesLockEx, $fileOp->storagePathsChanged() );
1334 // Optimization: if doing an EX lock anyway, don't also set an SH one
1335 $filesLockSh = array_diff( $filesLockSh, $filesLockEx );
1336 // Get a shared lock on the parent directory of each path changed
1337 $filesLockSh = array_merge( $filesLockSh, array_map( 'dirname', $filesLockEx ) );
1338 // Try to lock those files for the scope of this function...
1339 $scopeLockS = $this->getScopedFileLocks( $filesLockSh, LockManager
::LOCK_UW
, $status );
1340 $scopeLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
1341 if ( !$status->isOK() ) {
1342 wfProfileOut( __METHOD__
);
1343 return $status; // abort
1347 // Clear any cache entries (after locks acquired)
1348 $this->clearCache();
1350 // Actually attempt the operation batch...
1351 $subStatus = FileOp
::attemptBatch( $performOps, $opts );
1353 // Merge errors into status fields
1354 $status->merge( $subStatus );
1355 $status->success
= $subStatus->success
; // not done in merge()
1357 wfProfileOut( __METHOD__
);
1362 * @see FileBackendBase::clearCache()
1364 final public function clearCache( array $paths = null ) {
1365 if ( is_array( $paths ) ) {
1366 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1367 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1369 if ( $paths === null ) {
1370 $this->cache
= array();
1371 $this->expCache
= array();
1373 foreach ( $paths as $path ) {
1374 unset( $this->cache
[$path] );
1375 unset( $this->expCache
[$path] );
1378 $this->doClearCache( $paths );
1382 * Clears any additional stat caches for storage paths
1384 * @see FileBackendBase::clearCache()
1386 * @param $paths Array Storage paths (optional)
1389 protected function doClearCache( array $paths = null ) {}
1392 * Prune the inexpensive cache if it is too big to add an item
1396 protected function trimCache() {
1397 if ( count( $this->cache
) >= $this->maxCacheSize
) {
1398 reset( $this->cache
);
1399 unset( $this->cache
[key( $this->cache
)] );
1404 * Prune the expensive cache if it is too big to add an item
1408 protected function trimExpCache() {
1409 if ( count( $this->expCache
) >= $this->maxExpCacheSize
) {
1410 reset( $this->expCache
);
1411 unset( $this->expCache
[key( $this->expCache
)] );
1416 * Check if a container name is valid.
1417 * This checks for for length and illegal characters.
1419 * @param $container string
1422 final protected static function isValidContainerName( $container ) {
1423 // This accounts for Swift and S3 restrictions while leaving room
1424 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1425 // Note that matching strings URL encode to the same string;
1426 // in Swift, the length restriction is *after* URL encoding.
1427 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1431 * Splits a storage path into an internal container name,
1432 * an internal relative file name, and a container shard suffix.
1433 * Any shard suffix is already appended to the internal container name.
1434 * This also checks that the storage path is valid and within this backend.
1436 * If the container is sharded but a suffix could not be determined,
1437 * this means that the path can only refer to a directory and can only
1438 * be scanned by looking in all the container shards.
1440 * @param $storagePath string
1441 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1443 final protected function resolveStoragePath( $storagePath ) {
1444 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1445 if ( $backend === $this->name
) { // must be for this backend
1446 $relPath = self
::normalizeContainerPath( $relPath );
1447 if ( $relPath !== null ) {
1448 // Get shard for the normalized path if this container is sharded
1449 $cShard = $this->getContainerShard( $container, $relPath );
1450 // Validate and sanitize the relative path (backend-specific)
1451 $relPath = $this->resolveContainerPath( $container, $relPath );
1452 if ( $relPath !== null ) {
1453 // Prepend any wiki ID prefix to the container name
1454 $container = $this->fullContainerName( $container );
1455 if ( self
::isValidContainerName( $container ) ) {
1456 // Validate and sanitize the container name (backend-specific)
1457 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1458 if ( $container !== null ) {
1459 return array( $container, $relPath, $cShard );
1465 return array( null, null, null );
1469 * Like resolveStoragePath() except null values are returned if
1470 * the container is sharded and the shard could not be determined.
1472 * @see FileBackend::resolveStoragePath()
1474 * @param $storagePath string
1475 * @return Array (container, path) or (null, null) if invalid
1477 final protected function resolveStoragePathReal( $storagePath ) {
1478 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1479 if ( $cShard !== null ) {
1480 return array( $container, $relPath );
1482 return array( null, null );
1486 * Get the container name shard suffix for a given path.
1487 * Any empty suffix means the container is not sharded.
1489 * @param $container string Container name
1490 * @param $relStoragePath string Storage path relative to the container
1491 * @return string|null Returns null if shard could not be determined
1493 final protected function getContainerShard( $container, $relPath ) {
1494 $hashLevels = $this->getContainerHashLevels( $container );
1495 if ( $hashLevels === 1 ) { // 16 shards per container
1496 $hashDirRegex = '(?P<shard>[0-9a-f])';
1497 } elseif ( $hashLevels === 2 ) { // 256 shards per container
1498 $hashDirRegex = '[0-9a-f]/(?P<shard>[0-9a-f]{2})';
1500 return ''; // no sharding
1502 // Allow certain directories to be above the hash dirs so as
1503 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1504 // They must be 2+ chars to avoid any hash directory ambiguity.
1506 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1507 return '.' . $m['shard'];
1509 return null; // failed to match
1513 * Get the number of hash levels for a container.
1514 * If greater than 0, then all file storage paths within
1515 * the container are required to be hashed accordingly.
1517 * @param $container string
1520 final protected function getContainerHashLevels( $container ) {
1521 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1522 $hashLevels = (int)$this->shardViaHashLevels
[$container];
1523 if ( $hashLevels >= 0 && $hashLevels <= 2 ) {
1527 return 0; // no sharding
1531 * Get a list of full container shard suffixes for a container
1533 * @param $container string
1536 final protected function getContainerSuffixes( $container ) {
1538 $digits = $this->getContainerHashLevels( $container );
1539 if ( $digits > 0 ) {
1540 $numShards = 1 << ( $digits * 4 );
1541 for ( $index = 0; $index < $numShards; $index++
) {
1542 $shards[] = '.' . str_pad( dechex( $index ), $digits, '0', STR_PAD_LEFT
);
1549 * Get the full container name, including the wiki ID prefix
1551 * @param $container string
1554 final protected function fullContainerName( $container ) {
1555 if ( $this->wikiId
!= '' ) {
1556 return "{$this->wikiId}-$container";
1563 * Resolve a container name, checking if it's allowed by the backend.
1564 * This is intended for internal use, such as encoding illegal chars.
1565 * Subclasses can override this to be more restrictive.
1567 * @param $container string
1568 * @return string|null
1570 protected function resolveContainerName( $container ) {
1575 * Resolve a relative storage path, checking if it's allowed by the backend.
1576 * This is intended for internal use, such as encoding illegal chars or perhaps
1577 * getting absolute paths (e.g. FS based backends). Note that the relative path
1578 * may be the empty string (e.g. the path is simply to the container).
1580 * @param $container string Container name
1581 * @param $relStoragePath string Storage path relative to the container
1582 * @return string|null Path or null if not valid
1584 protected function resolveContainerPath( $container, $relStoragePath ) {
1585 return $relStoragePath;
1590 * FileBackend helper function to handle file listings that span container shards.
1591 * Do not use this class from places outside of FileBackend.
1593 * @ingroup FileBackend
1595 class FileBackendShardListIterator
implements Iterator
{
1596 /* @var FileBackend */
1601 protected $shardSuffixes;
1602 protected $container; // string
1603 protected $directory; // string
1605 /* @var Traversable */
1607 protected $curShard = 0; // integer
1608 protected $pos = 0; // integer
1611 * @param $backend FileBackend
1612 * @param $container string Full storage container name
1613 * @param $dir string Storage directory relative to container
1614 * @param $suffixes Array List of container shard suffixes
1615 * @param $params Array
1617 public function __construct(
1618 FileBackend
$backend, $container, $dir, array $suffixes, array $params
1620 $this->backend
= $backend;
1621 $this->container
= $container;
1622 $this->directory
= $dir;
1623 $this->shardSuffixes
= $suffixes;
1624 $this->params
= $params;
1627 public function current() {
1628 if ( is_array( $this->iter
) ) {
1629 return current( $this->iter
);
1631 return $this->iter
->current();
1635 public function key() {
1639 public function next() {
1641 if ( is_array( $this->iter
) ) {
1642 next( $this->iter
);
1644 $this->iter
->next();
1646 // Find the next non-empty shard if no elements are left
1647 $this->nextShardIteratorIfNotValid();
1651 * If the iterator for this container shard is out of items,
1652 * then move on to the next container that has items.
1653 * If there are none, then it advances to the last container.
1655 protected function nextShardIteratorIfNotValid() {
1656 while ( !$this->valid() ) {
1657 if ( ++
$this->curShard
>= count( $this->shardSuffixes
) ) {
1658 break; // no more container shards
1660 $this->setIteratorFromCurrentShard();
1664 protected function setIteratorFromCurrentShard() {
1665 $suffix = $this->shardSuffixes
[$this->curShard
];
1666 $this->iter
= $this->backend
->getFileListInternal(
1667 "{$this->container}{$suffix}", $this->directory
, $this->params
);
1670 public function rewind() {
1672 $this->curShard
= 0;
1673 $this->setIteratorFromCurrentShard();
1674 // Find the next non-empty shard if this one has no elements
1675 $this->nextShardIteratorIfNotValid();
1678 public function valid() {
1679 if ( $this->iter
== null ) {
1680 return false; // some failure?
1681 } elseif ( is_array( $this->iter
) ) {
1682 return ( current( $this->iter
) !== false ); // no paths can have this value
1684 return $this->iter
->valid();