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 typical file system (FS) notation, though any particular backend may
15 * not actually be using a local filesystem. Therefore, the paths are only virtual.
17 * FS-based backends are somewhat more restrictive due to the existence of real
18 * directory files; a regular file cannot have the same name as a directory. Other
19 * backends with virtual directories may not have this limitation. Callers should
20 * store files in such a way that no files and directories under the same path.
22 * Methods should avoid throwing exceptions at all costs.
23 * As a corollary, external dependencies should be kept to a minimum.
25 * @ingroup FileBackend
28 abstract class FileBackendBase
{
29 protected $name; // unique backend name
30 protected $wikiId; // unique wiki name
31 protected $readOnly; // string
32 /** @var LockManager */
33 protected $lockManager;
36 * Build a new object from configuration.
37 * This should only be called from within FileBackendGroup.
40 * 'name' : The unique name of this backend
41 * 'wikiId' : Prefix to container names that is unique to this wiki
42 * 'lockManager' : Registered name of a file lock manager to use
43 * 'readOnly' : Write operations are disallowed if this is a non-empty string.
44 * It should be an explanation for the backend being read-only.
46 * @param $config Array
48 public function __construct( array $config ) {
49 $this->name
= $config['name'];
50 $this->wikiId
= isset( $config['wikiId'] )
53 $this->lockManager
= LockManagerGroup
::singleton()->get( $config['lockManager'] );
54 $this->readOnly
= isset( $config['readOnly'] )
55 ?
(string)$config['readOnly']
60 * Get the unique backend name.
62 * We may have multiple different backends of the same type.
63 * For example, we can have two Swift backends using different proxies.
67 final public function getName() {
72 * This is the main entry point into the backend for write operations.
73 * Callers supply an ordered list of operations to perform as a transaction.
74 * If any serious errors occur, all attempted operations will be rolled back.
76 * $ops is an array of arrays. The outer array holds a list of operations.
77 * Each inner array is a set of key value pairs that specify an operation.
79 * Supported operations and their parameters:
80 * a) Create a new file in storage with the contents of a string
83 * 'dst' => <storage path>,
84 * 'content' => <string of new file contents>,
85 * 'overwriteDest' => <boolean>,
86 * 'overwriteSame' => <boolean>
88 * b) Copy a file system file into storage
91 * 'src' => <file system path>,
92 * 'dst' => <storage path>,
93 * 'overwriteDest' => <boolean>,
94 * 'overwriteSame' => <boolean>
96 * c) Copy a file within storage
99 * 'src' => <storage path>,
100 * 'dst' => <storage path>,
101 * 'overwriteDest' => <boolean>,
102 * 'overwriteSame' => <boolean>
104 * d) Move a file within storage
107 * 'src' => <storage path>,
108 * 'dst' => <storage path>,
109 * 'overwriteDest' => <boolean>,
110 * 'overwriteSame' => <boolean>
112 * e) Delete a file within storage
115 * 'src' => <storage path>,
116 * 'ignoreMissingSource' => <boolean>
118 * f) Concatenate a list of files within storage into a single temp file
120 * 'op' => 'concatenate',
121 * 'srcs' => <ordered array of storage paths>,
122 * 'dst' => <file system path to 0-byte temp file>
124 * g) Do nothing (no-op)
129 * Boolean flags for operations (operation-specific):
130 * 'ignoreMissingSource' : The operation will simply succeed and do
131 * nothing if the source file does not exist.
132 * 'overwriteDest' : Any destination file will be overwritten.
133 * 'overwriteSame' : An error will not be given if a file already
134 * exists at the destination that has the same
135 * contents as the new contents to be written there.
137 * $opts is an associative of boolean flags, including:
138 * 'ignoreErrors' : Errors that would normally cause a rollback do not.
139 * The remaining operations are still attempted if any fail.
140 * 'nonLocking' : No locks are acquired for the operations.
141 * This can increase performance for non-critical writes.
142 * This has no effect unless the 'ignoreErrors' flag is set.
143 * 'allowStale' : Don't require the latest available data.
144 * This can increase performance for non-critical writes.
145 * This has no effect unless the 'ignoreErrors' flag is set.
148 * This returns a Status, which contains all warnings and fatals that occured
149 * during the operation. The 'failCount', 'successCount', and 'success' members
150 * will reflect each operation attempted. The status will be "OK" unless any
151 * of the operations failed and the 'ignoreErrors' parameter was not set.
153 * @param $ops Array List of operations to execute in order
154 * @param $opts Array Batch operation options
157 final public function doOperations( array $ops, array $opts = array() ) {
158 if ( $this->readOnly
!= '' ) {
159 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
161 if ( empty( $opts['ignoreErrors'] ) ) { // sanity
162 unset( $opts['nonLocking'] );
163 unset( $opts['allowStale'] );
165 return $this->doOperationsInternal( $ops, $opts );
169 * @see FileBackendBase::doOperations()
171 abstract protected function doOperationsInternal( array $ops, array $opts );
174 * Same as doOperations() except it takes a single operation.
175 * If you are doing a batch of operations that should either
176 * all succeed or all fail, then use that function instead.
178 * @see FileBackendBase::doOperations()
180 * @param $op Array Operation
181 * @param $opts Array Operation options
184 final public function doOperation( array $op, array $opts = array() ) {
185 return $this->doOperations( array( $op ), $opts );
189 * Performs a single store operation.
190 * This sets $params['op'] to 'store' and passes it to doOperation().
192 * @see FileBackendBase::doOperation()
194 * @param $params Array Operation parameters
195 * @param $opts Array Operation options
198 final public function store( array $params, array $opts = array() ) {
199 $params['op'] = 'store';
200 return $this->doOperation( $params, $opts );
204 * Performs a single copy operation.
205 * This sets $params['op'] to 'copy' and passes it to doOperation().
207 * @see FileBackendBase::doOperation()
209 * @param $params Array Operation parameters
210 * @param $opts Array Operation options
213 final public function copy( array $params, array $opts = array() ) {
214 $params['op'] = 'copy';
215 return $this->doOperation( $params, $opts );
219 * Performs a single move operation.
220 * This sets $params['op'] to 'move' and passes it to doOperation().
222 * @see FileBackendBase::doOperation()
224 * @param $params Array Operation parameters
225 * @param $opts Array Operation options
228 final public function move( array $params, array $opts = array() ) {
229 $params['op'] = 'move';
230 return $this->doOperation( $params, $opts );
234 * Performs a single delete operation.
235 * This sets $params['op'] to 'delete' and passes it to doOperation().
237 * @see FileBackendBase::doOperation()
239 * @param $params Array Operation parameters
240 * @param $opts Array Operation options
243 final public function delete( array $params, array $opts = array() ) {
244 $params['op'] = 'delete';
245 return $this->doOperation( $params, $opts );
249 * Performs a single create operation.
250 * This sets $params['op'] to 'create' and passes it to doOperation().
252 * @see FileBackendBase::doOperation()
254 * @param $params Array Operation parameters
255 * @param $opts Array Operation options
258 final public function create( array $params, array $opts = array() ) {
259 $params['op'] = 'create';
260 return $this->doOperation( $params, $opts );
264 * Performs a single concatenate operation.
265 * This sets $params['op'] to 'concatenate' and passes it to doOperation().
267 * @see FileBackendBase::doOperation()
269 * @param $params Array Operation parameters
270 * @param $opts Array Operation options
273 final public function concatenate( array $params, array $opts = array() ) {
274 $params['op'] = 'concatenate';
275 return $this->doOperation( $params, $opts );
279 * Prepare a storage path for usage. This will create containers
280 * that don't yet exist or, on FS backends, create parent directories.
283 * dir : storage directory
285 * @param $params Array
288 abstract public function prepare( array $params );
291 * Take measures to block web access to a directory and
292 * the container it belongs to. FS backends might add .htaccess
293 * files wheras backends like Swift this might restrict container
294 * access to backend user that represents end-users in web request.
295 * This is not guaranteed to actually do anything.
298 * dir : storage directory
299 * noAccess : try to deny file access
300 * noListing : try to deny file listing
302 * @param $params Array
305 abstract public function secure( array $params );
308 * Clean up an empty storage directory.
309 * On FS backends, the directory will be deleted. Others may do nothing.
312 * dir : storage directory
314 * @param $params Array
317 abstract public function clean( array $params );
320 * Check if a file exists at a storage path in the backend.
323 * src : source storage path
324 * latest : use the latest available data
326 * @param $params Array
327 * @return bool|null Returns null on failure
329 abstract public function fileExists( array $params );
332 * Get the last-modified timestamp of the file at a storage path.
335 * src : source storage path
336 * latest : use the latest available data
338 * @param $params Array
339 * @return string|false TS_MW timestamp or false on failure
341 abstract public function getFileTimestamp( array $params );
344 * Get the contents of a file at a storage path in the backend.
345 * This should be avoided for potentially large files.
348 * src : source storage path
349 * latest : use the latest available data
351 * @param $params Array
352 * @return string|false Returns false on failure
354 abstract public function getFileContents( array $params );
357 * Get a SHA-1 hash of the file at a storage path in the backend.
360 * src : source storage path
361 * latest : use the latest available data
363 * @param $params Array
364 * @return string|false Hash string or false on failure
366 abstract public function getFileSha1Base36( array $params );
369 * Get the properties of the file at a storage path in the backend.
370 * Returns FSFile::placeholderProps() on failure.
373 * src : source storage path
374 * latest : use the latest available data
376 * @param $params Array
379 abstract public function getFileProps( array $params );
382 * Stream the file at a storage path in the backend.
383 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
384 * must be sent if streaming began, while none should be sent otherwise.
385 * Implementations should flush the output buffer before sending data.
388 * src : source storage path
389 * headers : additional HTTP headers to send on success
390 * latest : use the latest available data
392 * @param $params Array
395 abstract public function streamFile( array $params );
398 * Returns a file system file, identical to the file at a storage path.
399 * The file returned is either:
400 * a) A local copy of the file at a storage path in the backend.
401 * The temporary copy will have the same extension as the source.
402 * b) An original of the file at a storage path in the backend.
403 * Temporary files may be purged when the file object falls out of scope.
405 * Write operations should *never* be done on this file as some backends
406 * may do internal tracking or may be instances of FileBackendMultiWrite.
407 * In that later case, there are copies of the file that must stay in sync.
410 * src : source storage path
411 * latest : use the latest available data
413 * @param $params Array
414 * @return FSFile|null Returns null on failure
416 abstract public function getLocalReference( array $params );
419 * Get a local copy on disk of the file at a storage path in the backend.
420 * The temporary copy will have the same file extension as the source.
421 * Temporary files may be purged when the file object falls out of scope.
424 * src : source storage path
425 * latest : use the latest available data
427 * @param $params Array
428 * @return TempFSFile|null Returns null on failure
430 abstract public function getLocalCopy( array $params );
433 * Get an iterator to list out all object files under a storage directory.
434 * If the directory is of the form "mwstore://container", then all items in
435 * the container should be listed. If of the form "mwstore://container/dir",
436 * then all items under that container directory should be listed.
437 * Results should be storage paths relative to the given directory.
440 * dir : storage path directory
442 * @return Traversable|Array|null Returns null on failure
444 abstract public function getFileList( array $params );
447 * Lock the files at the given storage paths in the backend.
448 * This will either lock all the files or none (on failure).
450 * Callers should consider using getScopedFileLocks() instead.
452 * @param $paths Array Storage paths
453 * @param $type integer LockManager::LOCK_* constant
456 final public function lockFiles( array $paths, $type ) {
457 return $this->lockManager
->lock( $paths, $type );
461 * Unlock the files at the given storage paths in the backend.
463 * @param $paths Array Storage paths
464 * @param $type integer LockManager::LOCK_* constant
467 final public function unlockFiles( array $paths, $type ) {
468 return $this->lockManager
->unlock( $paths, $type );
472 * Lock the files at the given storage paths in the backend.
473 * This will either lock all the files or none (on failure).
474 * On failure, the status object will be updated with errors.
476 * Once the return value goes out scope, the locks will be released and
477 * the status updated. Unlock fatals will not change the status "OK" value.
479 * @param $paths Array Storage paths
480 * @param $type integer LockManager::LOCK_* constant
481 * @param $status Status Status to update on lock/unlock
482 * @return ScopedLock|null Returns null on failure
484 final public function getScopedFileLocks( array $paths, $type, Status
$status ) {
485 return ScopedLock
::factory( $this->lockManager
, $paths, $type, $status );
490 * Base class for all single-write backends.
491 * This class defines the methods as abstract that subclasses must implement.
493 * @ingroup FileBackend
496 abstract class FileBackend
extends FileBackendBase
{
498 protected $cache = array(); // (storage path => key => value)
499 protected $maxCacheSize = 50; // integer; max paths with entries
501 protected $shardViaHashLevels = array(); // (container name => integer)
504 * Create a file in the backend with the given contents.
505 * Do not call this function from places outside FileBackend and FileOp.
507 * content : the raw file contents
508 * dst : destination storage path
509 * overwriteDest : overwrite any file that exists at the destination
511 * @param $params Array
514 final public function createInternal( array $params ) {
515 $status = $this->doCreateInternal( $params );
516 $this->clearCache( array( $params['dst'] ) );
521 * @see FileBackend::createInternal()
523 abstract protected function doCreateInternal( array $params );
526 * Store a file into the backend from a file on disk.
527 * Do not call this function from places outside FileBackend and FileOp.
529 * src : source path on disk
530 * dst : destination storage path
531 * overwriteDest : overwrite any file that exists at the destination
533 * @param $params Array
536 final public function storeInternal( array $params ) {
537 $status = $this->doStoreInternal( $params );
538 $this->clearCache( array( $params['dst'] ) );
543 * @see FileBackend::storeInternal()
545 abstract protected function doStoreInternal( array $params );
548 * Copy a file from one storage path to another in the backend.
549 * Do not call this function from places outside FileBackend and FileOp.
551 * src : source storage path
552 * dst : destination storage path
553 * overwriteDest : overwrite any file that exists at the destination
555 * @param $params Array
558 final public function copyInternal( array $params ) {
559 $status = $this->doCopyInternal( $params );
560 $this->clearCache( array( $params['dst'] ) );
565 * @see FileBackend::copyInternal()
567 abstract protected function doCopyInternal( array $params );
570 * Delete a file at the storage path.
571 * Do not call this function from places outside FileBackend and FileOp.
573 * src : source storage path
574 * ignoreMissingSource : do nothing if the source file does not exist
576 * @param $params Array
579 final public function deleteInternal( array $params ) {
580 $status = $this->doDeleteInternal( $params );
581 $this->clearCache( array( $params['src'] ) );
586 * @see FileBackend::deleteInternal()
588 abstract protected function doDeleteInternal( array $params );
591 * Move a file from one storage path to another in the backend.
592 * Do not call this function from places outside FileBackend and FileOp.
594 * src : source storage path
595 * dst : destination storage path
596 * overwriteDest : overwrite any file that exists at the destination
598 * @param $params Array
601 final public function moveInternal( array $params ) {
602 $status = $this->doMoveInternal( $params );
603 $this->clearCache( array( $params['src'], $params['dst'] ) );
608 * @see FileBackend::moveInternal()
610 protected function doMoveInternal( array $params ) {
611 // Copy source to dest
612 $status = $this->copyInternal( $params );
613 if ( !$status->isOK() ) {
616 // Delete source (only fails due to races or medium going down)
617 $status->merge( $this->deleteInternal( array( 'src' => $params['src'] ) ) );
618 $status->setResult( true, $status->value
); // ignore delete() errors
623 * Combines files from several storage paths into a new file in the backend.
624 * Do not call this function from places outside FileBackend and FileOp.
626 * srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
627 * dst : file system path to 0-byte temp file
628 * overwriteDest : overwrite any file that exists at the destination
630 * @param $params Array
633 final public function concatenateInternal( array $params ) {
634 $status = $this->doConcatenateInternal( $params );
639 * @see FileBackend::concatenateInternal()
641 protected function doConcatenateInternal( array $params ) {
642 $status = Status
::newGood();
643 $tmpPath = $params['dst']; // convenience
645 // Check that the specified temp file is valid...
646 wfSuppressWarnings();
647 $ok = ( is_file( $tmpPath ) && !filesize( $tmpPath ) );
649 if ( !$ok ) { // not present or not empty
650 $status->fatal( 'backend-fail-opentemp', $tmpPath );
654 // Build up the temp file using the source chunks (in order)...
655 $tmpHandle = fopen( $tmpPath, 'a' );
656 if ( $tmpHandle === false ) {
657 $status->fatal( 'backend-fail-opentemp', $tmpPath );
660 foreach ( $params['srcs'] as $virtualSource ) {
661 // Get a local FS version of the chunk
662 $tmpFile = $this->getLocalReference( array( 'src' => $virtualSource ) );
664 $status->fatal( 'backend-fail-read', $virtualSource );
667 // Get a handle to the local FS version
668 $sourceHandle = fopen( $tmpFile->getPath(), 'r' );
669 if ( $sourceHandle === false ) {
670 fclose( $tmpHandle );
671 $status->fatal( 'backend-fail-read', $virtualSource );
674 // Append chunk to file (pass chunk size to avoid magic quotes)
675 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
676 fclose( $sourceHandle );
677 fclose( $tmpHandle );
678 $status->fatal( 'backend-fail-writetemp', $tmpPath );
681 fclose( $sourceHandle );
683 if ( !fclose( $tmpHandle ) ) {
684 $status->fatal( 'backend-fail-closetemp', $tmpPath );
692 * @see FileBackendBase::prepare()
694 final public function prepare( array $params ) {
695 $status = Status
::newGood();
696 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
697 if ( $dir === null ) {
698 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
699 return $status; // invalid storage path
701 if ( $shard !== null ) { // confined to a single container/shard
702 $status->merge( $this->doPrepare( $fullCont, $dir, $params ) );
703 } else { // directory is on several shards
704 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
705 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
706 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
707 $status->merge( $this->doPrepare( "{$fullCont}{$suffix}", $dir, $params ) );
714 * @see FileBackend::prepare()
716 protected function doPrepare( $container, $dir, array $params ) {
717 return Status
::newGood();
721 * @see FileBackendBase::secure()
723 final public function secure( array $params ) {
724 $status = Status
::newGood();
725 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
726 if ( $dir === null ) {
727 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
728 return $status; // invalid storage path
730 if ( $shard !== null ) { // confined to a single container/shard
731 $status->merge( $this->doSecure( $fullCont, $dir, $params ) );
732 } else { // directory is on several shards
733 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
734 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
735 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
736 $status->merge( $this->doSecure( "{$fullCont}{$suffix}", $dir, $params ) );
743 * @see FileBackend::secure()
745 protected function doSecure( $container, $dir, array $params ) {
746 return Status
::newGood();
750 * @see FileBackendBase::clean()
752 final public function clean( 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->doClean( $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->doClean( "{$fullCont}{$suffix}", $dir, $params ) );
772 * @see FileBackend::clean()
774 protected function doClean( $container, $dir, array $params ) {
775 return Status
::newGood();
779 * @see FileBackendBase::getFileContents()
781 public function getFileContents( array $params ) {
782 $tmpFile = $this->getLocalReference( $params );
786 wfSuppressWarnings();
787 $data = file_get_contents( $tmpFile->getPath() );
793 * @see FileBackendBase::getFileSha1Base36()
795 public function getFileSha1Base36( array $params ) {
796 $path = $params['src'];
797 if ( isset( $this->cache
[$path]['sha1'] ) ) {
798 return $this->cache
[$path]['sha1'];
800 $fsFile = $this->getLocalReference( $params );
804 $sha1 = $fsFile->getSha1Base36();
805 if ( $sha1 !== false ) { // don't cache negatives
806 $this->trimCache(); // limit memory
807 $this->cache
[$path]['sha1'] = $sha1;
814 * @see FileBackendBase::getFileProps()
816 public function getFileProps( array $params ) {
817 $fsFile = $this->getLocalReference( $params );
819 return FSFile
::placeholderProps();
821 return $fsFile->getProps();
826 * @see FileBackendBase::getLocalReference()
828 public function getLocalReference( array $params ) {
829 return $this->getLocalCopy( $params );
833 * @see FileBackendBase::streamFile()
835 public function streamFile( array $params ) {
836 $status = Status
::newGood();
838 $fsFile = $this->getLocalReference( $params );
840 $status->fatal( 'backend-fail-stream', $params['src'] );
844 $extraHeaders = isset( $params['headers'] )
848 $ok = StreamFile
::stream( $fsFile->getPath(), $extraHeaders, false );
850 $status->fatal( 'backend-fail-stream', $params['src'] );
858 * @see FileBackendBase::getFileList()
860 final public function getFileList( array $params ) {
861 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
862 if ( $dir === null ) { // invalid storage path
865 if ( $shard !== null ) {
866 // File listing is confined to a single container/shard
867 return $this->getFileListInternal( $fullCont, $dir, $params );
869 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
870 // File listing spans multiple containers/shards
871 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
872 return new ContainerShardListIterator( $this,
873 $fullCont, $this->getContainerSuffixes( $shortCont ), $params );
878 * Do not call this function from places outside FileBackend and ContainerFileListIterator
880 * @param $container string Resolved container name
881 * @param $dir string Resolved path relative to container
882 * @param $params Array
883 * @see FileBackend::getFileList()
885 abstract public function getFileListInternal( $container, $dir, array $params );
888 * Get the list of supported operations and their corresponding FileOp classes.
892 protected function supportedOperations() {
894 'store' => 'StoreFileOp',
895 'copy' => 'CopyFileOp',
896 'move' => 'MoveFileOp',
897 'delete' => 'DeleteFileOp',
898 'concatenate' => 'ConcatenateFileOp',
899 'create' => 'CreateFileOp',
900 'null' => 'NullFileOp'
905 * Return a list of FileOp objects from a list of operations.
906 * Do not call this function from places outside FileBackend.
908 * The result must have the same number of items as the input.
909 * An exception is thrown if an unsupported operation is requested.
911 * @param $ops Array Same format as doOperations()
912 * @return Array List of FileOp objects
913 * @throws MWException
915 final public function getOperations( array $ops ) {
916 $supportedOps = $this->supportedOperations();
918 $performOps = array(); // array of FileOp objects
919 // Build up ordered array of FileOps...
920 foreach ( $ops as $operation ) {
921 $opName = $operation['op'];
922 if ( isset( $supportedOps[$opName] ) ) {
923 $class = $supportedOps[$opName];
924 // Get params for this operation
925 $params = $operation;
926 // Append the FileOp class
927 $performOps[] = new $class( $this, $params );
929 throw new MWException( "Operation `$opName` is not supported." );
937 * @see FileBackendBase::doOperationsInternal()
939 protected function doOperationsInternal( array $ops, array $opts ) {
940 $status = Status
::newGood();
942 // Build up a list of FileOps...
943 $performOps = $this->getOperations( $ops );
945 // Acquire any locks as needed...
946 if ( empty( $opts['nonLocking'] ) ) {
947 // Build up a list of files to lock...
948 $filesLockEx = $filesLockSh = array();
949 foreach ( $performOps as $fileOp ) {
950 $filesLockSh = array_merge( $filesLockSh, $fileOp->storagePathsRead() );
951 $filesLockEx = array_merge( $filesLockEx, $fileOp->storagePathsChanged() );
953 // Optimization: if doing an EX lock anyway, don't also set an SH one
954 $filesLockSh = array_diff( $filesLockSh, $filesLockEx );
955 // Try to lock those files for the scope of this function...
956 $scopeLockS = $this->getScopedFileLocks( $filesLockSh, LockManager
::LOCK_UW
, $status );
957 $scopeLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
958 if ( !$status->isOK() ) {
959 return $status; // abort
963 // Clear any cache entries (after locks acquired)
965 // Actually attempt the operation batch...
966 $status->merge( FileOp
::attemptBatch( $performOps, $opts ) );
972 * Invalidate the file existence and property cache
974 * @param $paths Array Clear cache for specific files
977 final public function clearCache( array $paths = null ) {
978 if ( $paths === null ) {
979 $this->cache
= array();
981 foreach ( $paths as $path ) {
982 unset( $this->cache
[$path] );
988 * Prune the cache if it is too big to add an item
992 protected function trimCache() {
993 if ( count( $this->cache
) >= $this->maxCacheSize
) {
994 reset( $this->cache
);
995 $key = key( $this->cache
);
996 unset( $this->cache
[$key] );
1001 * Check if a given path is a mwstore:// path.
1002 * This does not do any actual validation or existence checks.
1004 * @param $path string
1007 final public static function isStoragePath( $path ) {
1008 return ( strpos( $path, 'mwstore://' ) === 0 );
1012 * Split a storage path (e.g. "mwstore://backend/container/path/to/object")
1013 * into a backend name, a container name, and a relative object path.
1015 * @param $storagePath string
1016 * @return Array (backend, container, rel object) or (null, null, null)
1018 final public static function splitStoragePath( $storagePath ) {
1019 if ( self
::isStoragePath( $storagePath ) ) {
1020 // Note: strlen( 'mwstore://' ) = 10
1021 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1022 if ( count( $parts ) == 3 ) {
1023 return $parts; // e.g. "backend/container/path"
1024 } elseif ( count( $parts ) == 2 ) {
1025 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
1028 return array( null, null, null );
1032 * Check if a container name is valid.
1033 * This checks for for length and illegal characters.
1035 * @param $container string
1038 final protected static function isValidContainerName( $container ) {
1039 // This accounts for Swift and S3 restrictions. Also note
1040 // that these urlencode to the same string, which is useful
1041 // since the Swift size limit is *after* URL encoding.
1042 // Limit to 200 to leave room for '.shard-XX' or '.segment'.
1043 return preg_match( '/^[a-zA-Z0-9._-]{1,200}$/u', $container );
1047 * Validate and normalize a relative storage path.
1048 * Null is returned if the path involves directory traversal.
1049 * Traversal is insecure for FS backends and broken for others.
1051 * @param $path string
1052 * @return string|null
1054 final protected static function normalizeStoragePath( $path ) {
1055 // Normalize directory separators
1056 $path = strtr( $path, '\\', '/' );
1057 // Use the same traversal protection as Title::secureAndSplit()
1058 if ( strpos( $path, '.' ) !== false ) {
1062 strpos( $path, './' ) === 0 ||
1063 strpos( $path, '../' ) === 0 ||
1064 strpos( $path, '/./' ) !== false ||
1065 strpos( $path, '/../' ) !== false
1074 * Splits a storage path into an internal container name,
1075 * an internal relative object name, and a container shard suffix.
1076 * Any shard suffix is already appended to the internal container name.
1077 * This also checks that the storage path is valid and within this backend.
1079 * If the container is sharded but a suffix could not be determined,
1080 * this means that the path can only refer to a directory and can only
1081 * be scanned by looking in all the container shards.
1083 * @param $storagePath string
1084 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1086 final protected function resolveStoragePath( $storagePath ) {
1087 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1088 if ( $backend === $this->name
) { // must be for this backend
1089 $relPath = self
::normalizeStoragePath( $relPath );
1090 if ( $relPath !== null ) {
1091 // Get shard for the normalized path if this container is sharded
1092 $cShard = $this->getContainerShard( $container, $relPath );
1093 // Validate and sanitize the relative path (backend-specific)
1094 $relPath = $this->resolveContainerPath( $container, $relPath );
1095 if ( $relPath !== null ) {
1096 // Prepend any wiki ID prefix to the container name
1097 $container = $this->fullContainerName( $container );
1098 if ( self
::isValidContainerName( $container ) ) {
1099 // Validate and sanitize the container name (backend-specific)
1100 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1101 if ( $container !== null ) {
1102 return array( $container, $relPath, $cShard );
1108 return array( null, null, null );
1112 * Like resolveStoragePath() except null values are returned if
1113 * the container is sharded and the shard could not be determined.
1115 * @see FileBackend::resolveStoragePath()
1117 * @param $storagePath string
1118 * @return Array (container, path) or (null, null) if invalid
1120 final protected function resolveStoragePathReal( $storagePath ) {
1121 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1122 if ( $cShard !== null ) {
1123 return array( $container, $relPath );
1125 return array( null, null );
1129 * Get the container name shard suffix for a given path.
1130 * Any empty suffix means the container is not sharded.
1132 * @param $container string Container name
1133 * @param $relStoragePath string Storage path relative to the container
1134 * @return string|null Returns null if shard could not be determined
1136 final protected function getContainerShard( $container, $relPath ) {
1137 $hashLevels = $this->getContainerHashLevels( $container );
1138 if ( $hashLevels === 1 ) { // 16 shards per container
1139 $hashDirRegex = '(?P<shard>[0-9a-f])';
1140 } elseif ( $hashLevels === 2 ) { // 256 shards per container
1141 $hashDirRegex = '[0-9a-f]/(?P<shard>[0-9a-f]{2})';
1143 return ''; // no sharding
1145 // Allow certain directories to be above the hash dirs so as
1146 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1147 // They must be 2+ chars to avoid any hash directory ambiguity.
1148 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1149 return '.shard-' . str_pad( $m['shard'], $hashLevels, '0', STR_PAD_LEFT
);
1151 return null; // failed to match
1155 * Get the number of hash levels for a container.
1156 * If greater than 0, then all file storage paths within
1157 * the container are required to be hashed accordingly.
1159 * @param $container string
1162 final protected function getContainerHashLevels( $container ) {
1163 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1164 $hashLevels = (int)$this->shardViaHashLevels
[$container];
1165 if ( $hashLevels >= 0 && $hashLevels <= 2 ) {
1169 return 0; // no sharding
1173 * Get a list of full container shard suffixes for a container
1175 * @param $container string
1178 final protected function getContainerSuffixes( $container ) {
1180 $digits = $this->getContainerHashLevels( $container );
1181 if ( $digits > 0 ) {
1182 $numShards = 1 << ( $digits * 4 );
1183 for ( $index = 0; $index < $numShards; $index++
) {
1184 $shards[] = '.shard-' . str_pad( dechex( $index ), $digits, '0', STR_PAD_LEFT
);
1191 * Get the full container name, including the wiki ID prefix
1193 * @param $container string
1196 final protected function fullContainerName( $container ) {
1197 if ( $this->wikiId
!= '' ) {
1198 return "{$this->wikiId}-$container";
1205 * Resolve a container name, checking if it's allowed by the backend.
1206 * This is intended for internal use, such as encoding illegal chars.
1207 * Subclasses can override this to be more restrictive.
1209 * @param $container string
1210 * @return string|null
1212 protected function resolveContainerName( $container ) {
1217 * Resolve a relative storage path, checking if it's allowed by the backend.
1218 * This is intended for internal use, such as encoding illegal chars or perhaps
1219 * getting absolute paths (e.g. FS based backends). Note that the relative path
1220 * may be the empty string (e.g. the path is simply to the container).
1222 * @param $container string Container name
1223 * @param $relStoragePath string Storage path relative to the container
1224 * @return string|null Path or null if not valid
1226 protected function resolveContainerPath( $container, $relStoragePath ) {
1227 return $relStoragePath;
1231 * Get the final extension from a storage or FS path
1233 * @param $path string
1236 final public static function extensionFromPath( $path ) {
1237 $i = strrpos( $path, '.' );
1238 return strtolower( $i ?
substr( $path, $i +
1 ) : '' );
1243 * FileBackend helper function to handle file listings that span container shards.
1244 * Do not use this class from places outside of FileBackend.
1246 * @ingroup FileBackend
1248 class ContainerShardListIterator
implements Iterator
{
1249 /* @var FileBackend */
1254 protected $shardSuffixes;
1255 protected $container; // string
1256 protected $directory; // string
1258 /* @var Traversable */
1260 protected $curShard = 0; // integer
1261 protected $pos = 0; // integer
1264 * @param $backend FileBackend
1265 * @param $container string Full storage container name
1266 * @param $dir string Storage directory relative to container
1267 * @param $suffixes Array List of container shard suffixes
1268 * @param $params Array
1270 public function __construct(
1271 FileBackend
$backend, $container, $dir, array $suffixes, array $params
1273 $this->backend
= $backend;
1274 $this->container
= $container;
1275 $this->directory
= $dir;
1276 $this->shardSuffixes
= $suffixes;
1277 $this->params
= $params;
1280 public function current() {
1281 if ( is_array( $this->iter
) ) {
1282 return current( $this->iter
);
1284 return $this->iter
->current();
1288 public function key() {
1292 public function next() {
1294 if ( is_array( $this->iter
) ) {
1295 next( $this->iter
);
1297 $this->iter
->next();
1299 // Find the next non-empty shard if no elements are left
1300 $this->nextShardIteratorIfNotValid();
1304 * If the iterator for this container shard is out of items,
1305 * then move on to the next container that has items.
1307 protected function nextShardIteratorIfNotValid() {
1308 while ( !$this->valid() ) {
1309 if ( ++
$this->curShard
>= count( $this->shardSuffixes
) ) {
1310 break; // no more container shards
1312 $this->setIteratorFromCurrentShard();
1316 protected function setIteratorFromCurrentShard() {
1317 $suffix = $this->shardSuffixes
[$this->curShard
];
1318 $this->iter
= $this->backend
->getFileListInternal(
1319 "{$this->container}{$suffix}", $this->directory
, $this->params
);
1322 public function rewind() {
1324 $this->curShard
= 0;
1325 $this->setIteratorFromCurrentShard();
1326 // Find the next non-empty shard if this one has no elements
1327 $this->nextShardIteratorIfNotValid();
1330 public function valid() {
1331 if ( $this->iter
== null ) {
1332 return false; // some failure?
1333 } elseif ( is_array( $this->iter
) ) {
1334 return ( current( $this->iter
) !== false ); // no paths can have this value
1336 return $this->iter
->valid();