3 * @defgroup FileBackend File backend
6 * File backend is used to interact with file storage systems,
7 * such as the local file system, NFS, or cloud storage systems.
11 * Base class for all file backends.
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License along
24 * with this program; if not, write to the Free Software Foundation, Inc.,
25 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26 * http://www.gnu.org/copyleft/gpl.html
29 * @ingroup FileBackend
30 * @author Aaron Schulz
34 * @brief Base class for all file backend classes (including multi-write backends).
36 * This class defines the methods as abstract that subclasses must implement.
37 * Outside callers can assume that all backends will have these functions.
39 * All "storage paths" are of the format "mwstore://<backend>/<container>/<path>".
40 * The <path> portion is a relative path that uses UNIX file system (FS) notation,
41 * though any particular backend may not actually be using a local filesystem.
42 * Therefore, the relative paths are only virtual.
44 * Backend contents are stored under wiki-specific container names by default.
45 * For legacy reasons, this has no effect for the FS backend class, and per-wiki
46 * segregation must be done by setting the container paths appropriately.
48 * FS-based backends are somewhat more restrictive due to the existence of real
49 * directory files; a regular file cannot have the same name as a directory. Other
50 * backends with virtual directories may not have this limitation. Callers should
51 * store files in such a way that no files and directories are under the same path.
53 * Methods should avoid throwing exceptions at all costs.
54 * As a corollary, external dependencies should be kept to a minimum.
56 * @ingroup FileBackend
59 abstract class FileBackend
{
60 protected $name; // string; unique backend name
61 protected $wikiId; // string; unique wiki name
62 protected $readOnly; // string; read-only explanation message
63 /** @var LockManager */
64 protected $lockManager;
65 /** @var FileJournal */
66 protected $fileJournal;
69 * Create a new backend instance from configuration.
70 * This should only be called from within FileBackendGroup.
73 * 'name' : The unique name of this backend.
74 * This should consist of alphanumberic, '-', and '_' characters.
75 * This name should not be changed after use.
76 * 'wikiId' : Prefix to container names that is unique to this wiki.
77 * It should only consist of alphanumberic, '-', and '_' characters.
78 * 'lockManager' : Registered name of a file lock manager to use.
79 * 'fileJournal' : File journal configuration; see FileJournal::factory().
80 * Journals simply log changes to files stored in the backend.
81 * 'readOnly' : Write operations are disallowed if this is a non-empty string.
82 * It should be an explanation for the backend being read-only.
84 * @param $config Array
86 public function __construct( array $config ) {
87 $this->name
= $config['name'];
88 if ( !preg_match( '!^[a-zA-Z0-9-_]{1,255}$!', $this->name
) ) {
89 throw new MWException( "Backend name `{$this->name}` is invalid." );
91 $this->wikiId
= isset( $config['wikiId'] )
93 : wfWikiID(); // e.g. "my_wiki-en_"
94 $this->lockManager
= ( $config['lockManager'] instanceof LockManager
)
95 ?
$config['lockManager']
96 : LockManagerGroup
::singleton()->get( $config['lockManager'] );
97 $this->fileJournal
= isset( $config['fileJournal'] )
98 ? FileJournal
::factory( $config['fileJournal'], $this->name
)
99 : FileJournal
::factory( array( 'class' => 'NullFileJournal' ), $this->name
);
100 $this->readOnly
= isset( $config['readOnly'] )
101 ?
(string)$config['readOnly']
106 * Get the unique backend name.
107 * We may have multiple different backends of the same type.
108 * For example, we can have two Swift backends using different proxies.
112 final public function getName() {
117 * Check if this backend is read-only
121 final public function isReadOnly() {
122 return ( $this->readOnly
!= '' );
126 * Get an explanatory message if this backend is read-only
128 * @return string|bool Returns false if the backend is not read-only
130 final public function getReadOnlyReason() {
131 return ( $this->readOnly
!= '' ) ?
$this->readOnly
: false;
135 * This is the main entry point into the backend for write operations.
136 * Callers supply an ordered list of operations to perform as a transaction.
137 * Files will be locked, the stat cache cleared, and then the operations attempted.
138 * If any serious errors occur, all attempted operations will be rolled back.
140 * $ops is an array of arrays. The outer array holds a list of operations.
141 * Each inner array is a set of key value pairs that specify an operation.
143 * Supported operations and their parameters:
144 * a) Create a new file in storage with the contents of a string
147 * 'dst' => <storage path>,
148 * 'content' => <string of new file contents>,
149 * 'overwrite' => <boolean>,
150 * 'overwriteSame' => <boolean>
152 * b) Copy a file system file into storage
155 * 'src' => <file system path>,
156 * 'dst' => <storage path>,
157 * 'overwrite' => <boolean>,
158 * 'overwriteSame' => <boolean>
160 * c) Copy a file within storage
163 * 'src' => <storage path>,
164 * 'dst' => <storage path>,
165 * 'overwrite' => <boolean>,
166 * 'overwriteSame' => <boolean>
168 * d) Move a file within storage
171 * 'src' => <storage path>,
172 * 'dst' => <storage path>,
173 * 'overwrite' => <boolean>,
174 * 'overwriteSame' => <boolean>
176 * e) Delete a file within storage
179 * 'src' => <storage path>,
180 * 'ignoreMissingSource' => <boolean>
182 * f) Do nothing (no-op)
187 * Boolean flags for operations (operation-specific):
188 * 'ignoreMissingSource' : The operation will simply succeed and do
189 * nothing if the source file does not exist.
190 * 'overwrite' : Any destination file will be overwritten.
191 * 'overwriteSame' : An error will not be given if a file already
192 * exists at the destination that has the same
193 * contents as the new contents to be written there.
195 * $opts is an associative of boolean flags, including:
196 * 'force' : Operation precondition errors no longer trigger an abort.
197 * Any remaining operations are still attempted. Unexpected
198 * failures may still cause remaning operations to be aborted.
199 * 'nonLocking' : No locks are acquired for the operations.
200 * This can increase performance for non-critical writes.
201 * This has no effect unless the 'force' flag is set.
202 * 'allowStale' : Don't require the latest available data.
203 * This can increase performance for non-critical writes.
204 * This has no effect unless the 'force' flag is set.
205 * 'nonJournaled' : Don't log this operation batch in the file journal.
206 * This limits the ability of recovery scripts.
208 * Remarks on locking:
209 * File system paths given to operations should refer to files that are
210 * already locked or otherwise safe from modification from other processes.
211 * Normally these files will be new temp files, which should be adequate.
214 * This returns a Status, which contains all warnings and fatals that occured
215 * during the operation. The 'failCount', 'successCount', and 'success' members
216 * will reflect each operation attempted. The status will be "OK" unless:
217 * a) unexpected operation errors occurred (network partitions, disk full...)
218 * b) significant operation errors occured and 'force' was not set
220 * @param $ops Array List of operations to execute in order
221 * @param $opts Array Batch operation options
224 final public function doOperations( array $ops, array $opts = array() ) {
225 if ( $this->isReadOnly() ) {
226 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
228 if ( empty( $opts['force'] ) ) { // sanity
229 unset( $opts['nonLocking'] );
230 unset( $opts['allowStale'] );
232 return $this->doOperationsInternal( $ops, $opts );
236 * @see FileBackend::doOperations()
238 abstract protected function doOperationsInternal( array $ops, array $opts );
241 * Same as doOperations() except it takes a single operation.
242 * If you are doing a batch of operations that should either
243 * all succeed or all fail, then use that function instead.
245 * @see FileBackend::doOperations()
247 * @param $op Array Operation
248 * @param $opts Array Operation options
251 final public function doOperation( array $op, array $opts = array() ) {
252 return $this->doOperations( array( $op ), $opts );
256 * Performs a single create operation.
257 * This sets $params['op'] to 'create' and passes it to doOperation().
259 * @see FileBackend::doOperation()
261 * @param $params Array Operation parameters
262 * @param $opts Array Operation options
265 final public function create( array $params, array $opts = array() ) {
266 $params['op'] = 'create';
267 return $this->doOperation( $params, $opts );
271 * Performs a single store operation.
272 * This sets $params['op'] to 'store' and passes it to doOperation().
274 * @see FileBackend::doOperation()
276 * @param $params Array Operation parameters
277 * @param $opts Array Operation options
280 final public function store( array $params, array $opts = array() ) {
281 $params['op'] = 'store';
282 return $this->doOperation( $params, $opts );
286 * Performs a single copy operation.
287 * This sets $params['op'] to 'copy' and passes it to doOperation().
289 * @see FileBackend::doOperation()
291 * @param $params Array Operation parameters
292 * @param $opts Array Operation options
295 final public function copy( array $params, array $opts = array() ) {
296 $params['op'] = 'copy';
297 return $this->doOperation( $params, $opts );
301 * Performs a single move operation.
302 * This sets $params['op'] to 'move' and passes it to doOperation().
304 * @see FileBackend::doOperation()
306 * @param $params Array Operation parameters
307 * @param $opts Array Operation options
310 final public function move( array $params, array $opts = array() ) {
311 $params['op'] = 'move';
312 return $this->doOperation( $params, $opts );
316 * Performs a single delete operation.
317 * This sets $params['op'] to 'delete' and passes it to doOperation().
319 * @see FileBackend::doOperation()
321 * @param $params Array Operation parameters
322 * @param $opts Array Operation options
325 final public function delete( array $params, array $opts = array() ) {
326 $params['op'] = 'delete';
327 return $this->doOperation( $params, $opts );
331 * Concatenate a list of storage files into a single file system file.
332 * The target path should refer to a file that is already locked or
333 * otherwise safe from modification from other processes. Normally,
334 * the file will be a new temp file, which should be adequate.
336 * srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
337 * dst : file system path to 0-byte temp file
339 * @param $params Array Operation parameters
342 abstract public function concatenate( array $params );
345 * Prepare a storage directory for usage.
346 * This will create any required containers and parent directories.
347 * Backends using key/value stores only need to create the container.
350 * dir : storage directory
352 * @param $params Array
355 final public function prepare( array $params ) {
356 if ( $this->isReadOnly() ) {
357 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
359 return $this->doPrepare( $params );
363 * @see FileBackend::prepare()
365 abstract protected function doPrepare( array $params );
368 * Take measures to block web access to a storage directory and
369 * the container it belongs to. FS backends might add .htaccess
370 * files whereas key/value store backends might restrict container
371 * access to the auth user that represents end-users in web request.
372 * This is not guaranteed to actually do anything.
375 * dir : storage directory
376 * noAccess : try to deny file access
377 * noListing : try to deny file listing
379 * @param $params Array
382 final public function secure( array $params ) {
383 if ( $this->isReadOnly() ) {
384 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
386 $status = $this->doPrepare( $params ); // dir must exist to restrict it
387 if ( $status->isOK() ) {
388 $status->merge( $this->doSecure( $params ) );
394 * @see FileBackend::secure()
396 abstract protected function doSecure( array $params );
399 * Delete a storage directory if it is empty.
400 * Backends using key/value stores may do nothing unless the directory
401 * is that of an empty container, in which case it should be deleted.
404 * dir : storage directory
405 * recursive : recursively delete empty subdirectories first (@since 1.20)
407 * @param $params Array
410 final public function clean( array $params ) {
411 if ( $this->isReadOnly() ) {
412 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
414 return $this->doClean( $params );
418 * @see FileBackend::clean()
420 abstract protected function doClean( array $params );
423 * Check if a file exists at a storage path in the backend.
424 * This returns false if only a directory exists at the path.
427 * src : source storage path
428 * latest : use the latest available data
430 * @param $params Array
431 * @return bool|null Returns null on failure
433 abstract public function fileExists( array $params );
436 * Get the last-modified timestamp of the file at a storage path.
439 * src : source storage path
440 * latest : use the latest available data
442 * @param $params Array
443 * @return string|bool TS_MW timestamp or false on failure
445 abstract public function getFileTimestamp( array $params );
448 * Get the contents of a file at a storage path in the backend.
449 * This should be avoided for potentially large files.
452 * src : source storage path
453 * latest : use the latest available data
455 * @param $params Array
456 * @return string|bool Returns false on failure
458 abstract public function getFileContents( array $params );
461 * Get the size (bytes) of a file at a storage path in the backend.
464 * src : source storage path
465 * latest : use the latest available data
467 * @param $params Array
468 * @return integer|bool Returns false on failure
470 abstract public function getFileSize( array $params );
473 * Get quick information about a file at a storage path in the backend.
474 * If the file does not exist, then this returns false.
475 * Otherwise, the result is an associative array that includes:
476 * mtime : the last-modified timestamp (TS_MW)
477 * size : the file size (bytes)
478 * Additional values may be included for internal use only.
481 * src : source storage path
482 * latest : use the latest available data
484 * @param $params Array
485 * @return Array|bool|null Returns null on failure
487 abstract public function getFileStat( array $params );
490 * Get a SHA-1 hash of the file at a storage path in the backend.
493 * src : source storage path
494 * latest : use the latest available data
496 * @param $params Array
497 * @return string|bool Hash string or false on failure
499 abstract public function getFileSha1Base36( array $params );
502 * Get the properties of the file at a storage path in the backend.
503 * Returns FSFile::placeholderProps() on failure.
506 * src : source storage path
507 * latest : use the latest available data
509 * @param $params Array
512 abstract public function getFileProps( array $params );
515 * Stream the file at a storage path in the backend.
516 * If the file does not exists, a 404 error will be given.
517 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
518 * must be sent if streaming began, while none should be sent otherwise.
519 * Implementations should flush the output buffer before sending data.
522 * src : source storage path
523 * headers : additional HTTP headers to send on success
524 * latest : use the latest available data
526 * @param $params Array
529 abstract public function streamFile( array $params );
532 * Returns a file system file, identical to the file at a storage path.
533 * The file returned is either:
534 * a) A local copy of the file at a storage path in the backend.
535 * The temporary copy will have the same extension as the source.
536 * b) An original of the file at a storage path in the backend.
537 * Temporary files may be purged when the file object falls out of scope.
539 * Write operations should *never* be done on this file as some backends
540 * may do internal tracking or may be instances of FileBackendMultiWrite.
541 * In that later case, there are copies of the file that must stay in sync.
542 * Additionally, further calls to this function may return the same file.
545 * src : source storage path
546 * latest : use the latest available data
548 * @param $params Array
549 * @return FSFile|null Returns null on failure
551 abstract public function getLocalReference( array $params );
554 * Get a local copy on disk of the file at a storage path in the backend.
555 * The temporary copy will have the same file extension as the source.
556 * Temporary files may be purged when the file object falls out of scope.
559 * src : source storage path
560 * latest : use the latest available data
562 * @param $params Array
563 * @return TempFSFile|null Returns null on failure
565 abstract public function getLocalCopy( array $params );
568 * Check if a directory exists at a given storage path.
569 * Backends using key/value stores will check if the path is a
570 * virtual directory, meaning there are files under the given directory.
572 * Storage backends with eventual consistency might return stale data.
575 * dir : storage directory
577 * @return bool|null Returns null on failure
580 abstract public function directoryExists( array $params );
583 * Get an iterator to list *all* directories under a storage directory.
584 * If the directory is of the form "mwstore://backend/container",
585 * then all directories in the container should be listed.
586 * If the directory is of form "mwstore://backend/container/dir",
587 * then all directories directly under that directory should be listed.
588 * Results should be storage directories relative to the given directory.
590 * Storage backends with eventual consistency might return stale data.
593 * dir : storage directory
594 * topOnly : only return direct child dirs of the directory
596 * @return Traversable|Array|null Returns null on failure
599 abstract public function getDirectoryList( array $params );
602 * Same as FileBackend::getDirectoryList() except only lists
603 * directories that are immediately under the given directory.
605 * Storage backends with eventual consistency might return stale data.
608 * dir : storage directory
610 * @return Traversable|Array|null Returns null on failure
613 final public function getTopDirectoryList( array $params ) {
614 return $this->getDirectoryList( array( 'topOnly' => true ) +
$params );
618 * Get an iterator to list *all* stored files under a storage directory.
619 * If the directory is of the form "mwstore://backend/container",
620 * then all files in the container should be listed.
621 * If the directory is of form "mwstore://backend/container/dir",
622 * then all files under that directory should be listed.
623 * Results should be storage paths relative to the given directory.
625 * Storage backends with eventual consistency might return stale data.
628 * dir : storage directory
629 * topOnly : only return direct child files of the directory (@since 1.20)
631 * @return Traversable|Array|null Returns null on failure
633 abstract public function getFileList( array $params );
636 * Same as FileBackend::getFileList() except only lists
637 * files that are immediately under the given directory.
639 * Storage backends with eventual consistency might return stale data.
642 * dir : storage directory
644 * @return Traversable|Array|null Returns null on failure
647 final public function getTopFileList( array $params ) {
648 return $this->getFileList( array( 'topOnly' => true ) +
$params );
652 * Invalidate any in-process file existence and property cache.
653 * If $paths is given, then only the cache for those files will be cleared.
655 * @param $paths Array Storage paths (optional)
658 public function clearCache( array $paths = null ) {}
661 * Lock the files at the given storage paths in the backend.
662 * This will either lock all the files or none (on failure).
664 * Callers should consider using getScopedFileLocks() instead.
666 * @param $paths Array Storage paths
667 * @param $type integer LockManager::LOCK_* constant
670 final public function lockFiles( array $paths, $type ) {
671 return $this->lockManager
->lock( $paths, $type );
675 * Unlock the files at the given storage paths in the backend.
677 * @param $paths Array Storage paths
678 * @param $type integer LockManager::LOCK_* constant
681 final public function unlockFiles( array $paths, $type ) {
682 return $this->lockManager
->unlock( $paths, $type );
686 * Lock the files at the given storage paths in the backend.
687 * This will either lock all the files or none (on failure).
688 * On failure, the status object will be updated with errors.
690 * Once the return value goes out scope, the locks will be released and
691 * the status updated. Unlock fatals will not change the status "OK" value.
693 * @param $paths Array Storage paths
694 * @param $type integer LockManager::LOCK_* constant
695 * @param $status Status Status to update on lock/unlock
696 * @return ScopedLock|null Returns null on failure
698 final public function getScopedFileLocks( array $paths, $type, Status
$status ) {
699 return ScopedLock
::factory( $this->lockManager
, $paths, $type, $status );
703 * Get the root storage path of this backend.
704 * All container paths are "subdirectories" of this path.
706 * @return string Storage path
709 final public function getRootStoragePath() {
710 return "mwstore://{$this->name}";
714 * Check if a given path is a "mwstore://" path.
715 * This does not do any further validation or any existence checks.
717 * @param $path string
720 final public static function isStoragePath( $path ) {
721 return ( strpos( $path, 'mwstore://' ) === 0 );
725 * Split a storage path into a backend name, a container name,
726 * and a relative file path. The relative path may be the empty string.
727 * This does not do any path normalization or traversal checks.
729 * @param $storagePath string
730 * @return Array (backend, container, rel object) or (null, null, null)
732 final public static function splitStoragePath( $storagePath ) {
733 if ( self
::isStoragePath( $storagePath ) ) {
734 // Remove the "mwstore://" prefix and split the path
735 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
736 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
737 if ( count( $parts ) == 3 ) {
738 return $parts; // e.g. "backend/container/path"
740 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
744 return array( null, null, null );
748 * Normalize a storage path by cleaning up directory separators.
749 * Returns null if the path is not of the format of a valid storage path.
751 * @param $storagePath string
752 * @return string|null
754 final public static function normalizeStoragePath( $storagePath ) {
755 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
756 if ( $relPath !== null ) { // must be for this backend
757 $relPath = self
::normalizeContainerPath( $relPath );
758 if ( $relPath !== null ) {
759 return ( $relPath != '' )
760 ?
"mwstore://{$backend}/{$container}/{$relPath}"
761 : "mwstore://{$backend}/{$container}";
768 * Get the parent storage directory of a storage path.
769 * This returns a path like "mwstore://backend/container",
770 * "mwstore://backend/container/...", or null if there is no parent.
772 * @param $storagePath string
773 * @return string|null
775 final public static function parentStoragePath( $storagePath ) {
776 $storagePath = dirname( $storagePath );
777 list( $b, $cont, $rel ) = self
::splitStoragePath( $storagePath );
778 return ( $rel === null ) ?
null : $storagePath;
782 * Get the final extension from a storage or FS path
784 * @param $path string
787 final public static function extensionFromPath( $path ) {
788 $i = strrpos( $path, '.' );
789 return strtolower( $i ?
substr( $path, $i +
1 ) : '' );
793 * Check if a relative path has no directory traversals
795 * @param $path string
799 final public static function isPathTraversalFree( $path ) {
800 return ( self
::normalizeContainerPath( $path ) !== null );
804 * Validate and normalize a relative storage path.
805 * Null is returned if the path involves directory traversal.
806 * Traversal is insecure for FS backends and broken for others.
808 * This uses the same traversal protection as Title::secureAndSplit().
810 * @param $path string Storage path relative to a container
811 * @return string|null
813 final protected static function normalizeContainerPath( $path ) {
814 // Normalize directory separators
815 $path = strtr( $path, '\\', '/' );
816 // Collapse any consecutive directory separators
817 $path = preg_replace( '![/]{2,}!', '/', $path );
818 // Remove any leading directory separator
819 $path = ltrim( $path, '/' );
820 // Use the same traversal protection as Title::secureAndSplit()
821 if ( strpos( $path, '.' ) !== false ) {
825 strpos( $path, './' ) === 0 ||
826 strpos( $path, '../' ) === 0 ||
827 strpos( $path, '/./' ) !== false ||
828 strpos( $path, '/../' ) !== false