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.
12 * @ingroup FileBackend
13 * @author Aaron Schulz
17 * @brief Base class for all file backend classes (including multi-write backends).
19 * This class defines the methods as abstract that subclasses must implement.
20 * Outside callers can assume that all backends will have these functions.
22 * All "storage paths" are of the format "mwstore://<backend>/<container>/<path>".
23 * The <path> portion is a relative path that uses UNIX file system (FS) notation,
24 * though any particular backend may not actually be using a local filesystem.
25 * Therefore, the relative paths are only virtual.
27 * Backend contents are stored under wiki-specific container names by default.
28 * For legacy reasons, this has no effect for the FS backend class, and per-wiki
29 * segregation must be done by setting the container paths appropriately.
31 * FS-based backends are somewhat more restrictive due to the existence of real
32 * directory files; a regular file cannot have the same name as a directory. Other
33 * backends with virtual directories may not have this limitation. Callers should
34 * store files in such a way that no files and directories are under the same path.
36 * Methods should avoid throwing exceptions at all costs.
37 * As a corollary, external dependencies should be kept to a minimum.
39 * @ingroup FileBackend
42 abstract class FileBackend
{
43 protected $name; // string; unique backend name
44 protected $wikiId; // string; unique wiki name
45 protected $readOnly; // string; read-only explanation message
46 /** @var LockManager */
47 protected $lockManager;
48 /** @var FileJournal */
49 protected $fileJournal;
52 * Create a new backend instance from configuration.
53 * This should only be called from within FileBackendGroup.
56 * 'name' : The unique name of this backend.
57 * This should consist of alphanumberic, '-', and '_' characters.
58 * This name should not be changed after use.
59 * 'wikiId' : Prefix to container names that is unique to this wiki.
60 * This should consist of alphanumberic, '-', and '_' characters.
61 * 'lockManager' : Registered name of a file lock manager to use.
62 * 'readOnly' : Write operations are disallowed if this is a non-empty string.
63 * It should be an explanation for the backend being read-only.
65 * @param $config Array
67 public function __construct( array $config ) {
68 $this->name
= $config['name'];
69 if ( !preg_match( '!^[a-zA-Z0-9-_]{1,255}$!', $this->name
) ) {
70 throw new MWException( "Backend name `{$this->name}` is invalid." );
72 $this->wikiId
= isset( $config['wikiId'] )
74 : wfWikiID(); // e.g. "my_wiki-en_"
75 $this->lockManager
= ( $config['lockManager'] instanceof LockManager
)
76 ?
$config['lockManager']
77 : LockManagerGroup
::singleton()->get( $config['lockManager'] );
78 $this->fileJournal
= isset( $config['fileJournal'] )
79 ? FileJournal
::factory( $config['fileJournal'], $this->name
)
80 : FileJournal
::factory( array( 'class' => 'NullFileJournal' ), $this->name
);
81 $this->readOnly
= isset( $config['readOnly'] )
82 ?
(string)$config['readOnly']
87 * Get the unique backend name.
88 * We may have multiple different backends of the same type.
89 * For example, we can have two Swift backends using different proxies.
93 final public function getName() {
98 * Check if this backend is read-only
102 final public function isReadOnly() {
103 return ( $this->readOnly
!= '' );
107 * Get an explanatory message if this backend is read-only
109 * @return string|bool Returns falls if the backend is not read-only
111 final public function getReadOnlyReason() {
112 return ( $this->readOnly
!= '' ) ?
$this->readOnly
: false;
116 * This is the main entry point into the backend for write operations.
117 * Callers supply an ordered list of operations to perform as a transaction.
118 * Files will be locked, the stat cache cleared, and then the operations attempted.
119 * If any serious errors occur, all attempted operations will be rolled back.
121 * $ops is an array of arrays. The outer array holds a list of operations.
122 * Each inner array is a set of key value pairs that specify an operation.
124 * Supported operations and their parameters:
125 * a) Create a new file in storage with the contents of a string
128 * 'dst' => <storage path>,
129 * 'content' => <string of new file contents>,
130 * 'overwrite' => <boolean>,
131 * 'overwriteSame' => <boolean>
133 * b) Copy a file system file into storage
136 * 'src' => <file system path>,
137 * 'dst' => <storage path>,
138 * 'overwrite' => <boolean>,
139 * 'overwriteSame' => <boolean>
141 * c) Copy a file within storage
144 * 'src' => <storage path>,
145 * 'dst' => <storage path>,
146 * 'overwrite' => <boolean>,
147 * 'overwriteSame' => <boolean>
149 * d) Move a file within storage
152 * 'src' => <storage path>,
153 * 'dst' => <storage path>,
154 * 'overwrite' => <boolean>,
155 * 'overwriteSame' => <boolean>
157 * e) Delete a file within storage
160 * 'src' => <storage path>,
161 * 'ignoreMissingSource' => <boolean>
163 * f) Do nothing (no-op)
168 * Boolean flags for operations (operation-specific):
169 * 'ignoreMissingSource' : The operation will simply succeed and do
170 * nothing if the source file does not exist.
171 * 'overwrite' : Any destination file will be overwritten.
172 * 'overwriteSame' : An error will not be given if a file already
173 * exists at the destination that has the same
174 * contents as the new contents to be written there.
176 * $opts is an associative of boolean flags, including:
177 * 'force' : Errors that would normally cause a rollback do not.
178 * The remaining operations are still attempted if any fail.
179 * 'nonLocking' : No locks are acquired for the operations.
180 * This can increase performance for non-critical writes.
181 * This has no effect unless the 'force' flag is set.
182 * 'allowStale' : Don't require the latest available data.
183 * This can increase performance for non-critical writes.
184 * This has no effect unless the 'force' flag is set.
185 * 'nonJournaled' : Don't log this operation batch in the file journal.
186 * This limits the ability of recovery scripts.
188 * Remarks on locking:
189 * File system paths given to operations should refer to files that are
190 * already locked or otherwise safe from modification from other processes.
191 * Normally these files will be new temp files, which should be adequate.
194 * This returns a Status, which contains all warnings and fatals that occured
195 * during the operation. The 'failCount', 'successCount', and 'success' members
196 * will reflect each operation attempted. The status will be "OK" unless:
197 * a) unexpected operation errors occurred (network partitions, disk full...)
198 * b) significant operation errors occured and 'force' was not set
200 * @param $ops Array List of operations to execute in order
201 * @param $opts Array Batch operation options
204 final public function doOperations( array $ops, array $opts = array() ) {
205 if ( $this->isReadOnly() ) {
206 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
208 if ( empty( $opts['force'] ) ) { // sanity
209 unset( $opts['nonLocking'] );
210 unset( $opts['allowStale'] );
212 return $this->doOperationsInternal( $ops, $opts );
216 * @see FileBackend::doOperations()
218 abstract protected function doOperationsInternal( array $ops, array $opts );
221 * Same as doOperations() except it takes a single operation.
222 * If you are doing a batch of operations that should either
223 * all succeed or all fail, then use that function instead.
225 * @see FileBackend::doOperations()
227 * @param $op Array Operation
228 * @param $opts Array Operation options
231 final public function doOperation( array $op, array $opts = array() ) {
232 return $this->doOperations( array( $op ), $opts );
236 * Performs a single create operation.
237 * This sets $params['op'] to 'create' and passes it to doOperation().
239 * @see FileBackend::doOperation()
241 * @param $params Array Operation parameters
242 * @param $opts Array Operation options
245 final public function create( array $params, array $opts = array() ) {
246 $params['op'] = 'create';
247 return $this->doOperation( $params, $opts );
251 * Performs a single store operation.
252 * This sets $params['op'] to 'store' and passes it to doOperation().
254 * @see FileBackend::doOperation()
256 * @param $params Array Operation parameters
257 * @param $opts Array Operation options
260 final public function store( array $params, array $opts = array() ) {
261 $params['op'] = 'store';
262 return $this->doOperation( $params, $opts );
266 * Performs a single copy operation.
267 * This sets $params['op'] to 'copy' and passes it to doOperation().
269 * @see FileBackend::doOperation()
271 * @param $params Array Operation parameters
272 * @param $opts Array Operation options
275 final public function copy( array $params, array $opts = array() ) {
276 $params['op'] = 'copy';
277 return $this->doOperation( $params, $opts );
281 * Performs a single move operation.
282 * This sets $params['op'] to 'move' and passes it to doOperation().
284 * @see FileBackend::doOperation()
286 * @param $params Array Operation parameters
287 * @param $opts Array Operation options
290 final public function move( array $params, array $opts = array() ) {
291 $params['op'] = 'move';
292 return $this->doOperation( $params, $opts );
296 * Performs a single delete operation.
297 * This sets $params['op'] to 'delete' and passes it to doOperation().
299 * @see FileBackend::doOperation()
301 * @param $params Array Operation parameters
302 * @param $opts Array Operation options
305 final public function delete( array $params, array $opts = array() ) {
306 $params['op'] = 'delete';
307 return $this->doOperation( $params, $opts );
311 * Concatenate a list of storage files into a single file system file.
312 * The target path should refer to a file that is already locked or
313 * otherwise safe from modification from other processes. Normally,
314 * the file will be a new temp file, which should be adequate.
316 * srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
317 * dst : file system path to 0-byte temp file
319 * @param $params Array Operation parameters
322 abstract public function concatenate( array $params );
325 * Prepare a storage directory for usage.
326 * This will create any required containers and parent directories.
327 * Backends using key/value stores only need to create the container.
330 * dir : storage directory
332 * @param $params Array
335 final public function prepare( array $params ) {
336 if ( $this->isReadOnly() ) {
337 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
339 return $this->doPrepare( $params );
343 * @see FileBackend::prepare()
345 abstract protected function doPrepare( array $params );
348 * Take measures to block web access to a storage directory and
349 * the container it belongs to. FS backends might add .htaccess
350 * files whereas key/value store backends might restrict container
351 * access to the auth user that represents end-users in web request.
352 * This is not guaranteed to actually do anything.
355 * dir : storage directory
356 * noAccess : try to deny file access
357 * noListing : try to deny file listing
359 * @param $params Array
362 final public function secure( array $params ) {
363 if ( $this->isReadOnly() ) {
364 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
366 $status = $this->doPrepare( $params ); // dir must exist to restrict it
367 if ( $status->isOK() ) {
368 $status->merge( $this->doSecure( $params ) );
374 * @see FileBackend::secure()
376 abstract protected function doSecure( array $params );
379 * Delete a storage directory if it is empty.
380 * Backends using key/value stores may do nothing unless the directory
381 * is that of an empty container, in which case it should be deleted.
384 * dir : storage directory
386 * @param $params Array
389 final public function clean( array $params ) {
390 if ( $this->isReadOnly() ) {
391 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
393 return $this->doClean( $params );
397 * @see FileBackend::clean()
399 abstract protected function doClean( array $params );
402 * Check if a file exists at a storage path in the backend.
403 * This returns false if only a directory exists at the path.
406 * src : source storage path
407 * latest : use the latest available data
409 * @param $params Array
410 * @return bool|null Returns null on failure
412 abstract public function fileExists( array $params );
415 * Get the last-modified timestamp of the file at a storage path.
418 * src : source storage path
419 * latest : use the latest available data
421 * @param $params Array
422 * @return string|bool TS_MW timestamp or false on failure
424 abstract public function getFileTimestamp( array $params );
427 * Get the contents of a file at a storage path in the backend.
428 * This should be avoided for potentially large files.
431 * src : source storage path
432 * latest : use the latest available data
434 * @param $params Array
435 * @return string|bool Returns false on failure
437 abstract public function getFileContents( array $params );
440 * Get the size (bytes) of a file at a storage path in the backend.
443 * src : source storage path
444 * latest : use the latest available data
446 * @param $params Array
447 * @return integer|bool Returns false on failure
449 abstract public function getFileSize( array $params );
452 * Get quick information about a file at a storage path in the backend.
453 * If the file does not exist, then this returns false.
454 * Otherwise, the result is an associative array that includes:
455 * mtime : the last-modified timestamp (TS_MW)
456 * size : the file size (bytes)
457 * Additional values may be included for internal use only.
460 * src : source storage path
461 * latest : use the latest available data
463 * @param $params Array
464 * @return Array|bool|null Returns null on failure
466 abstract public function getFileStat( array $params );
469 * Get a SHA-1 hash of the file at a storage path in the backend.
472 * src : source storage path
473 * latest : use the latest available data
475 * @param $params Array
476 * @return string|bool Hash string or false on failure
478 abstract public function getFileSha1Base36( array $params );
481 * Get the properties of the file at a storage path in the backend.
482 * Returns FSFile::placeholderProps() on failure.
485 * src : source storage path
486 * latest : use the latest available data
488 * @param $params Array
491 abstract public function getFileProps( array $params );
494 * Stream the file at a storage path in the backend.
495 * If the file does not exists, a 404 error will be given.
496 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
497 * must be sent if streaming began, while none should be sent otherwise.
498 * Implementations should flush the output buffer before sending data.
501 * src : source storage path
502 * headers : additional HTTP headers to send on success
503 * latest : use the latest available data
505 * @param $params Array
508 abstract public function streamFile( array $params );
511 * Returns a file system file, identical to the file at a storage path.
512 * The file returned is either:
513 * a) A local copy of the file at a storage path in the backend.
514 * The temporary copy will have the same extension as the source.
515 * b) An original of the file at a storage path in the backend.
516 * Temporary files may be purged when the file object falls out of scope.
518 * Write operations should *never* be done on this file as some backends
519 * may do internal tracking or may be instances of FileBackendMultiWrite.
520 * In that later case, there are copies of the file that must stay in sync.
521 * Additionally, further calls to this function may return the same file.
524 * src : source storage path
525 * latest : use the latest available data
527 * @param $params Array
528 * @return FSFile|null Returns null on failure
530 abstract public function getLocalReference( array $params );
533 * Get a local copy on disk of the file at a storage path in the backend.
534 * The temporary copy will have the same file extension as the source.
535 * Temporary files may be purged when the file object falls out of scope.
538 * src : source storage path
539 * latest : use the latest available data
541 * @param $params Array
542 * @return TempFSFile|null Returns null on failure
544 abstract public function getLocalCopy( array $params );
547 * Get an iterator to list out all stored files under a storage directory.
548 * If the directory is of the form "mwstore://backend/container",
549 * then all files in the container should be listed.
550 * If the directory is of form "mwstore://backend/container/dir",
551 * then all files under that container directory should be listed.
552 * Results should be storage paths relative to the given directory.
554 * Storage backends with eventual consistency might return stale data.
557 * dir : storage path directory
559 * @return Traversable|Array|null Returns null on failure
561 abstract public function getFileList( array $params );
564 * Invalidate any in-process file existence and property cache.
565 * If $paths is given, then only the cache for those files will be cleared.
567 * @param $paths Array Storage paths (optional)
570 public function clearCache( array $paths = null ) {}
573 * Lock the files at the given storage paths in the backend.
574 * This will either lock all the files or none (on failure).
576 * Callers should consider using getScopedFileLocks() instead.
578 * @param $paths Array Storage paths
579 * @param $type integer LockManager::LOCK_* constant
582 final public function lockFiles( array $paths, $type ) {
583 return $this->lockManager
->lock( $paths, $type );
587 * Unlock the files at the given storage paths in the backend.
589 * @param $paths Array Storage paths
590 * @param $type integer LockManager::LOCK_* constant
593 final public function unlockFiles( array $paths, $type ) {
594 return $this->lockManager
->unlock( $paths, $type );
598 * Lock the files at the given storage paths in the backend.
599 * This will either lock all the files or none (on failure).
600 * On failure, the status object will be updated with errors.
602 * Once the return value goes out scope, the locks will be released and
603 * the status updated. Unlock fatals will not change the status "OK" value.
605 * @param $paths Array Storage paths
606 * @param $type integer LockManager::LOCK_* constant
607 * @param $status Status Status to update on lock/unlock
608 * @return ScopedLock|null Returns null on failure
610 final public function getScopedFileLocks( array $paths, $type, Status
$status ) {
611 return ScopedLock
::factory( $this->lockManager
, $paths, $type, $status );
615 * Check if a given path is a "mwstore://" path.
616 * This does not do any further validation or any existence checks.
618 * @param $path string
621 final public static function isStoragePath( $path ) {
622 return ( strpos( $path, 'mwstore://' ) === 0 );
626 * Split a storage path into a backend name, a container name,
627 * and a relative file path. The relative path may be the empty string.
628 * This does not do any path normalization or traversal checks.
630 * @param $storagePath string
631 * @return Array (backend, container, rel object) or (null, null, null)
633 final public static function splitStoragePath( $storagePath ) {
634 if ( self
::isStoragePath( $storagePath ) ) {
635 // Remove the "mwstore://" prefix and split the path
636 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
637 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
638 if ( count( $parts ) == 3 ) {
639 return $parts; // e.g. "backend/container/path"
641 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
645 return array( null, null, null );
649 * Normalize a storage path by cleaning up directory separators.
650 * Returns null if the path is not of the format of a valid storage path.
652 * @param $storagePath string
653 * @return string|null
655 final public static function normalizeStoragePath( $storagePath ) {
656 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
657 if ( $relPath !== null ) { // must be for this backend
658 $relPath = self
::normalizeContainerPath( $relPath );
659 if ( $relPath !== null ) {
660 return ( $relPath != '' )
661 ?
"mwstore://{$backend}/{$container}/{$relPath}"
662 : "mwstore://{$backend}/{$container}";
669 * Get the parent storage directory of a storage path.
670 * This returns a path like "mwstore://backend/container",
671 * "mwstore://backend/container/...", or null if there is no parent.
673 * @param $storagePath string
674 * @return string|null
676 final public static function parentStoragePath( $storagePath ) {
677 $storagePath = dirname( $storagePath );
678 list( $b, $cont, $rel ) = self
::splitStoragePath( $storagePath );
679 return ( $rel === null ) ?
null : $storagePath;
683 * Get the final extension from a storage or FS path
685 * @param $path string
688 final public static function extensionFromPath( $path ) {
689 $i = strrpos( $path, '.' );
690 return strtolower( $i ?
substr( $path, $i +
1 ) : '' );
694 * Validate and normalize a relative storage path.
695 * Null is returned if the path involves directory traversal.
696 * Traversal is insecure for FS backends and broken for others.
698 * @param $path string Storage path relative to a container
699 * @return string|null
701 final protected static function normalizeContainerPath( $path ) {
702 // Normalize directory separators
703 $path = strtr( $path, '\\', '/' );
704 // Collapse any consecutive directory separators
705 $path = preg_replace( '![/]{2,}!', '/', $path );
706 // Remove any leading directory separator
707 $path = ltrim( $path, '/' );
708 // Use the same traversal protection as Title::secureAndSplit()
709 if ( strpos( $path, '.' ) !== false ) {
713 strpos( $path, './' ) === 0 ||
714 strpos( $path, '../' ) === 0 ||
715 strpos( $path, '/./' ) !== false ||
716 strpos( $path, '/../' ) !== false