3 * Base class for all backends using particular storage medium.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup FileBackend
22 * @author Aaron Schulz
26 * @brief Base class for all backends using particular storage medium.
28 * This class defines the methods as abstract that subclasses must implement.
29 * Outside callers should *not* use functions with "Internal" in the name.
31 * The FileBackend operations are implemented using basic functions
32 * such as storeInternal(), copyInternal(), deleteInternal() and the like.
33 * This class is also responsible for path resolution and sanitization.
35 * @ingroup FileBackend
38 abstract class FileBackendStore
extends FileBackend
{
39 /** @var WANObjectCache */
41 /** @var ProcessCacheLRU Map of paths to small (RAM/disk) cache items */
42 protected $cheapCache;
43 /** @var ProcessCacheLRU Map of paths to large (RAM/disk) cache items */
44 protected $expensiveCache;
46 /** @var array Map of container names to sharding config */
47 protected $shardViaHashLevels = [];
49 /** @var callable Method to get the MIME type of files */
50 protected $mimeCallback;
52 protected $maxFileSize = 4294967296; // integer bytes (4GiB)
54 const CACHE_TTL
= 10; // integer; TTL in seconds for process cache entries
55 const CACHE_CHEAP_SIZE
= 500; // integer; max entries in "cheap cache"
56 const CACHE_EXPENSIVE_SIZE
= 5; // integer; max entries in "expensive cache"
59 * @see FileBackend::__construct()
60 * Additional $config params include:
61 * - wanCache : WANObjectCache object to use for persistent caching.
62 * - mimeCallback : Callback that takes (storage path, content, file system path) and
63 * returns the MIME type of the file or 'unknown/unknown'. The file
64 * system path parameter should be used if the content one is null.
66 * @param array $config
68 public function __construct( array $config ) {
69 parent
::__construct( $config );
70 $this->mimeCallback
= isset( $config['mimeCallback'] )
71 ?
$config['mimeCallback']
73 $this->memCache
= WANObjectCache
::newEmpty(); // disabled by default
74 $this->cheapCache
= new ProcessCacheLRU( self
::CACHE_CHEAP_SIZE
);
75 $this->expensiveCache
= new ProcessCacheLRU( self
::CACHE_EXPENSIVE_SIZE
);
79 * Get the maximum allowable file size given backend
80 * medium restrictions and basic performance constraints.
81 * Do not call this function from places outside FileBackend and FileOp.
85 final public function maxFileSizeInternal() {
86 return $this->maxFileSize
;
90 * Check if a file can be created or changed at a given storage path.
91 * FS backends should check if the parent directory exists, files can be
92 * written under it, and that any file already there is writable.
93 * Backends using key/value stores should check if the container exists.
95 * @param string $storagePath
98 abstract public function isPathUsableInternal( $storagePath );
101 * Create a file in the backend with the given contents.
102 * This will overwrite any file that exists at the destination.
103 * Do not call this function from places outside FileBackend and FileOp.
106 * - content : the raw file contents
107 * - dst : destination storage path
108 * - headers : HTTP header name/value map
109 * - async : StatusValue will be returned immediately if supported.
110 * If the StatusValue is OK, then its value field will be
111 * set to a FileBackendStoreOpHandle object.
112 * - dstExists : Whether a file exists at the destination (optimization).
113 * Callers can use "false" if no existing file is being changed.
115 * @param array $params
116 * @return StatusValue
118 final public function createInternal( array $params ) {
119 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
120 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
121 $status = $this->newStatus( 'backend-fail-maxsize',
122 $params['dst'], $this->maxFileSizeInternal() );
124 $status = $this->doCreateInternal( $params );
125 $this->clearCache( [ $params['dst'] ] );
126 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
127 $this->deleteFileCache( $params['dst'] ); // persistent cache
135 * @see FileBackendStore::createInternal()
136 * @param array $params
137 * @return StatusValue
139 abstract protected function doCreateInternal( array $params );
142 * Store a file into the backend from a file on disk.
143 * This will overwrite any file that exists at the destination.
144 * Do not call this function from places outside FileBackend and FileOp.
147 * - src : source path on disk
148 * - dst : destination storage path
149 * - headers : HTTP header name/value map
150 * - async : StatusValue will be returned immediately if supported.
151 * If the StatusValue is OK, then its value field will be
152 * set to a FileBackendStoreOpHandle object.
153 * - dstExists : Whether a file exists at the destination (optimization).
154 * Callers can use "false" if no existing file is being changed.
156 * @param array $params
157 * @return StatusValue
159 final public function storeInternal( array $params ) {
160 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
161 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
162 $status = $this->newStatus( 'backend-fail-maxsize',
163 $params['dst'], $this->maxFileSizeInternal() );
165 $status = $this->doStoreInternal( $params );
166 $this->clearCache( [ $params['dst'] ] );
167 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
168 $this->deleteFileCache( $params['dst'] ); // persistent cache
176 * @see FileBackendStore::storeInternal()
177 * @param array $params
178 * @return StatusValue
180 abstract protected function doStoreInternal( array $params );
183 * Copy a file from one storage path to another in the backend.
184 * This will overwrite any file that exists at the destination.
185 * Do not call this function from places outside FileBackend and FileOp.
188 * - src : source storage path
189 * - dst : destination storage path
190 * - ignoreMissingSource : do nothing if the source file does not exist
191 * - headers : HTTP header name/value map
192 * - async : StatusValue will be returned immediately if supported.
193 * If the StatusValue is OK, then its value field will be
194 * set to a FileBackendStoreOpHandle object.
195 * - dstExists : Whether a file exists at the destination (optimization).
196 * Callers can use "false" if no existing file is being changed.
198 * @param array $params
199 * @return StatusValue
201 final public function copyInternal( array $params ) {
202 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
203 $status = $this->doCopyInternal( $params );
204 $this->clearCache( [ $params['dst'] ] );
205 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
206 $this->deleteFileCache( $params['dst'] ); // persistent cache
213 * @see FileBackendStore::copyInternal()
214 * @param array $params
215 * @return StatusValue
217 abstract protected function doCopyInternal( array $params );
220 * Delete a file at the storage path.
221 * Do not call this function from places outside FileBackend and FileOp.
224 * - src : source storage path
225 * - ignoreMissingSource : do nothing if the source file does not exist
226 * - async : StatusValue will be returned immediately if supported.
227 * If the StatusValue is OK, then its value field will be
228 * set to a FileBackendStoreOpHandle object.
230 * @param array $params
231 * @return StatusValue
233 final public function deleteInternal( array $params ) {
234 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
235 $status = $this->doDeleteInternal( $params );
236 $this->clearCache( [ $params['src'] ] );
237 $this->deleteFileCache( $params['src'] ); // persistent cache
242 * @see FileBackendStore::deleteInternal()
243 * @param array $params
244 * @return StatusValue
246 abstract protected function doDeleteInternal( array $params );
249 * Move a file from one storage path to another in the backend.
250 * This will overwrite any file that exists at the destination.
251 * Do not call this function from places outside FileBackend and FileOp.
254 * - src : source storage path
255 * - dst : destination storage path
256 * - ignoreMissingSource : do nothing if the source file does not exist
257 * - headers : HTTP header name/value map
258 * - async : StatusValue will be returned immediately if supported.
259 * If the StatusValue is OK, then its value field will be
260 * set to a FileBackendStoreOpHandle object.
261 * - dstExists : Whether a file exists at the destination (optimization).
262 * Callers can use "false" if no existing file is being changed.
264 * @param array $params
265 * @return StatusValue
267 final public function moveInternal( array $params ) {
268 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
269 $status = $this->doMoveInternal( $params );
270 $this->clearCache( [ $params['src'], $params['dst'] ] );
271 $this->deleteFileCache( $params['src'] ); // persistent cache
272 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
273 $this->deleteFileCache( $params['dst'] ); // persistent cache
280 * @see FileBackendStore::moveInternal()
281 * @param array $params
282 * @return StatusValue
284 protected function doMoveInternal( array $params ) {
285 unset( $params['async'] ); // two steps, won't work here :)
286 $nsrc = FileBackend
::normalizeStoragePath( $params['src'] );
287 $ndst = FileBackend
::normalizeStoragePath( $params['dst'] );
288 // Copy source to dest
289 $status = $this->copyInternal( $params );
290 if ( $nsrc !== $ndst && $status->isOK() ) {
291 // Delete source (only fails due to races or network problems)
292 $status->merge( $this->deleteInternal( [ 'src' => $params['src'] ] ) );
293 $status->setResult( true, $status->value
); // ignore delete() errors
300 * Alter metadata for a file at the storage path.
301 * Do not call this function from places outside FileBackend and FileOp.
304 * - src : source storage path
305 * - headers : HTTP header name/value map
306 * - async : StatusValue will be returned immediately if supported.
307 * If the StatusValue is OK, then its value field will be
308 * set to a FileBackendStoreOpHandle object.
310 * @param array $params
311 * @return StatusValue
313 final public function describeInternal( array $params ) {
314 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
315 if ( count( $params['headers'] ) ) {
316 $status = $this->doDescribeInternal( $params );
317 $this->clearCache( [ $params['src'] ] );
318 $this->deleteFileCache( $params['src'] ); // persistent cache
320 $status = $this->newStatus(); // nothing to do
327 * @see FileBackendStore::describeInternal()
328 * @param array $params
329 * @return StatusValue
331 protected function doDescribeInternal( array $params ) {
332 return $this->newStatus();
336 * No-op file operation that does nothing.
337 * Do not call this function from places outside FileBackend and FileOp.
339 * @param array $params
340 * @return StatusValue
342 final public function nullInternal( array $params ) {
343 return $this->newStatus();
346 final public function concatenate( array $params ) {
347 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
348 $status = $this->newStatus();
350 // Try to lock the source files for the scope of this function
351 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager
::LOCK_UW
, $status );
352 if ( $status->isOK() ) {
353 // Actually do the file concatenation...
354 $start_time = microtime( true );
355 $status->merge( $this->doConcatenate( $params ) );
356 $sec = microtime( true ) - $start_time;
357 if ( !$status->isOK() ) {
358 $this->logger
->error( get_class( $this ) . "-{$this->name}" .
359 " failed to concatenate " . count( $params['srcs'] ) . " file(s) [$sec sec]" );
367 * @see FileBackendStore::concatenate()
368 * @param array $params
369 * @return StatusValue
371 protected function doConcatenate( array $params ) {
372 $status = $this->newStatus();
373 $tmpPath = $params['dst']; // convenience
374 unset( $params['latest'] ); // sanity
376 // Check that the specified temp file is valid...
377 MediaWiki\
suppressWarnings();
378 $ok = ( is_file( $tmpPath ) && filesize( $tmpPath ) == 0 );
379 MediaWiki\restoreWarnings
();
380 if ( !$ok ) { // not present or not empty
381 $status->fatal( 'backend-fail-opentemp', $tmpPath );
386 // Get local FS versions of the chunks needed for the concatenation...
387 $fsFiles = $this->getLocalReferenceMulti( $params );
388 foreach ( $fsFiles as $path => &$fsFile ) {
389 if ( !$fsFile ) { // chunk failed to download?
390 $fsFile = $this->getLocalReference( [ 'src' => $path ] );
391 if ( !$fsFile ) { // retry failed?
392 $status->fatal( 'backend-fail-read', $path );
398 unset( $fsFile ); // unset reference so we can reuse $fsFile
400 // Get a handle for the destination temp file
401 $tmpHandle = fopen( $tmpPath, 'ab' );
402 if ( $tmpHandle === false ) {
403 $status->fatal( 'backend-fail-opentemp', $tmpPath );
408 // Build up the temp file using the source chunks (in order)...
409 foreach ( $fsFiles as $virtualSource => $fsFile ) {
410 // Get a handle to the local FS version
411 $sourceHandle = fopen( $fsFile->getPath(), 'rb' );
412 if ( $sourceHandle === false ) {
413 fclose( $tmpHandle );
414 $status->fatal( 'backend-fail-read', $virtualSource );
418 // Append chunk to file (pass chunk size to avoid magic quotes)
419 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
420 fclose( $sourceHandle );
421 fclose( $tmpHandle );
422 $status->fatal( 'backend-fail-writetemp', $tmpPath );
426 fclose( $sourceHandle );
428 if ( !fclose( $tmpHandle ) ) {
429 $status->fatal( 'backend-fail-closetemp', $tmpPath );
434 clearstatcache(); // temp file changed
439 final protected function doPrepare( array $params ) {
440 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
441 $status = $this->newStatus();
443 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
444 if ( $dir === null ) {
445 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
447 return $status; // invalid storage path
450 if ( $shard !== null ) { // confined to a single container/shard
451 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
452 } else { // directory is on several shards
453 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
454 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
455 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
456 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
464 * @see FileBackendStore::doPrepare()
465 * @param string $container
467 * @param array $params
468 * @return StatusValue
470 protected function doPrepareInternal( $container, $dir, array $params ) {
471 return $this->newStatus();
474 final protected function doSecure( array $params ) {
475 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
476 $status = $this->newStatus();
478 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
479 if ( $dir === null ) {
480 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
482 return $status; // invalid storage path
485 if ( $shard !== null ) { // confined to a single container/shard
486 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
487 } else { // directory is on several shards
488 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
489 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
490 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
491 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
499 * @see FileBackendStore::doSecure()
500 * @param string $container
502 * @param array $params
503 * @return StatusValue
505 protected function doSecureInternal( $container, $dir, array $params ) {
506 return $this->newStatus();
509 final protected function doPublish( array $params ) {
510 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
511 $status = $this->newStatus();
513 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
514 if ( $dir === null ) {
515 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
517 return $status; // invalid storage path
520 if ( $shard !== null ) { // confined to a single container/shard
521 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
522 } else { // directory is on several shards
523 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
524 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
525 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
526 $status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
534 * @see FileBackendStore::doPublish()
535 * @param string $container
537 * @param array $params
538 * @return StatusValue
540 protected function doPublishInternal( $container, $dir, array $params ) {
541 return $this->newStatus();
544 final protected function doClean( array $params ) {
545 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
546 $status = $this->newStatus();
548 // Recursive: first delete all empty subdirs recursively
549 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
550 $subDirsRel = $this->getTopDirectoryList( [ 'dir' => $params['dir'] ] );
551 if ( $subDirsRel !== null ) { // no errors
552 foreach ( $subDirsRel as $subDirRel ) {
553 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
554 $status->merge( $this->doClean( [ 'dir' => $subDir ] +
$params ) );
556 unset( $subDirsRel ); // free directory for rmdir() on Windows (for FS backends)
560 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
561 if ( $dir === null ) {
562 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
564 return $status; // invalid storage path
567 // Attempt to lock this directory...
568 $filesLockEx = [ $params['dir'] ];
569 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
570 if ( !$status->isOK() ) {
571 return $status; // abort
574 if ( $shard !== null ) { // confined to a single container/shard
575 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
576 $this->deleteContainerCache( $fullCont ); // purge cache
577 } else { // directory is on several shards
578 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
579 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
580 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
581 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
582 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
590 * @see FileBackendStore::doClean()
591 * @param string $container
593 * @param array $params
594 * @return StatusValue
596 protected function doCleanInternal( $container, $dir, array $params ) {
597 return $this->newStatus();
600 final public function fileExists( array $params ) {
601 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
602 $stat = $this->getFileStat( $params );
604 return ( $stat === null ) ?
null : (bool)$stat; // null => failure
607 final public function getFileTimestamp( array $params ) {
608 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
609 $stat = $this->getFileStat( $params );
611 return $stat ?
$stat['mtime'] : false;
614 final public function getFileSize( array $params ) {
615 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
616 $stat = $this->getFileStat( $params );
618 return $stat ?
$stat['size'] : false;
621 final public function getFileStat( array $params ) {
622 $path = self
::normalizeStoragePath( $params['src'] );
623 if ( $path === null ) {
624 return false; // invalid storage path
626 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
627 $latest = !empty( $params['latest'] ); // use latest data?
628 if ( !$latest && !$this->cheapCache
->has( $path, 'stat', self
::CACHE_TTL
) ) {
629 $this->primeFileCache( [ $path ] ); // check persistent cache
631 if ( $this->cheapCache
->has( $path, 'stat', self
::CACHE_TTL
) ) {
632 $stat = $this->cheapCache
->get( $path, 'stat' );
633 // If we want the latest data, check that this cached
634 // value was in fact fetched with the latest available data.
635 if ( is_array( $stat ) ) {
636 if ( !$latest ||
$stat['latest'] ) {
639 } elseif ( in_array( $stat, [ 'NOT_EXIST', 'NOT_EXIST_LATEST' ] ) ) {
640 if ( !$latest ||
$stat === 'NOT_EXIST_LATEST' ) {
645 $stat = $this->doGetFileStat( $params );
646 if ( is_array( $stat ) ) { // file exists
647 // Strongly consistent backends can automatically set "latest"
648 $stat['latest'] = isset( $stat['latest'] ) ?
$stat['latest'] : $latest;
649 $this->cheapCache
->set( $path, 'stat', $stat );
650 $this->setFileCache( $path, $stat ); // update persistent cache
651 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
652 $this->cheapCache
->set( $path, 'sha1',
653 [ 'hash' => $stat['sha1'], 'latest' => $latest ] );
655 if ( isset( $stat['xattr'] ) ) { // some backends store headers/metadata
656 $stat['xattr'] = self
::normalizeXAttributes( $stat['xattr'] );
657 $this->cheapCache
->set( $path, 'xattr',
658 [ 'map' => $stat['xattr'], 'latest' => $latest ] );
660 } elseif ( $stat === false ) { // file does not exist
661 $this->cheapCache
->set( $path, 'stat', $latest ?
'NOT_EXIST_LATEST' : 'NOT_EXIST' );
662 $this->cheapCache
->set( $path, 'xattr', [ 'map' => false, 'latest' => $latest ] );
663 $this->cheapCache
->set( $path, 'sha1', [ 'hash' => false, 'latest' => $latest ] );
664 $this->logger
->debug( __METHOD__
. ": File $path does not exist.\n" );
665 } else { // an error occurred
666 $this->logger
->warning( __METHOD__
. ": Could not stat file $path.\n" );
673 * @see FileBackendStore::getFileStat()
674 * @param array $params
676 abstract protected function doGetFileStat( array $params );
678 public function getFileContentsMulti( array $params ) {
679 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
681 $params = $this->setConcurrencyFlags( $params );
682 $contents = $this->doGetFileContentsMulti( $params );
688 * @see FileBackendStore::getFileContentsMulti()
689 * @param array $params
692 protected function doGetFileContentsMulti( array $params ) {
694 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
695 MediaWiki\
suppressWarnings();
696 $contents[$path] = $fsFile ?
file_get_contents( $fsFile->getPath() ) : false;
697 MediaWiki\restoreWarnings
();
703 final public function getFileXAttributes( array $params ) {
704 $path = self
::normalizeStoragePath( $params['src'] );
705 if ( $path === null ) {
706 return false; // invalid storage path
708 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
709 $latest = !empty( $params['latest'] ); // use latest data?
710 if ( $this->cheapCache
->has( $path, 'xattr', self
::CACHE_TTL
) ) {
711 $stat = $this->cheapCache
->get( $path, 'xattr' );
712 // If we want the latest data, check that this cached
713 // value was in fact fetched with the latest available data.
714 if ( !$latest ||
$stat['latest'] ) {
718 $fields = $this->doGetFileXAttributes( $params );
719 $fields = is_array( $fields ) ? self
::normalizeXAttributes( $fields ) : false;
720 $this->cheapCache
->set( $path, 'xattr', [ 'map' => $fields, 'latest' => $latest ] );
726 * @see FileBackendStore::getFileXAttributes()
727 * @param array $params
728 * @return bool|string
730 protected function doGetFileXAttributes( array $params ) {
731 return [ 'headers' => [], 'metadata' => [] ]; // not supported
734 final public function getFileSha1Base36( array $params ) {
735 $path = self
::normalizeStoragePath( $params['src'] );
736 if ( $path === null ) {
737 return false; // invalid storage path
739 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
740 $latest = !empty( $params['latest'] ); // use latest data?
741 if ( $this->cheapCache
->has( $path, 'sha1', self
::CACHE_TTL
) ) {
742 $stat = $this->cheapCache
->get( $path, 'sha1' );
743 // If we want the latest data, check that this cached
744 // value was in fact fetched with the latest available data.
745 if ( !$latest ||
$stat['latest'] ) {
746 return $stat['hash'];
749 $hash = $this->doGetFileSha1Base36( $params );
750 $this->cheapCache
->set( $path, 'sha1', [ 'hash' => $hash, 'latest' => $latest ] );
756 * @see FileBackendStore::getFileSha1Base36()
757 * @param array $params
758 * @return bool|string
760 protected function doGetFileSha1Base36( array $params ) {
761 $fsFile = $this->getLocalReference( $params );
765 return $fsFile->getSha1Base36();
769 final public function getFileProps( array $params ) {
770 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
771 $fsFile = $this->getLocalReference( $params );
772 $props = $fsFile ?
$fsFile->getProps() : FSFile
::placeholderProps();
777 final public function getLocalReferenceMulti( array $params ) {
778 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
780 $params = $this->setConcurrencyFlags( $params );
782 $fsFiles = []; // (path => FSFile)
783 $latest = !empty( $params['latest'] ); // use latest data?
784 // Reuse any files already in process cache...
785 foreach ( $params['srcs'] as $src ) {
786 $path = self
::normalizeStoragePath( $src );
787 if ( $path === null ) {
788 $fsFiles[$src] = null; // invalid storage path
789 } elseif ( $this->expensiveCache
->has( $path, 'localRef' ) ) {
790 $val = $this->expensiveCache
->get( $path, 'localRef' );
791 // If we want the latest data, check that this cached
792 // value was in fact fetched with the latest available data.
793 if ( !$latest ||
$val['latest'] ) {
794 $fsFiles[$src] = $val['object'];
798 // Fetch local references of any remaning files...
799 $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
800 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
801 $fsFiles[$path] = $fsFile;
802 if ( $fsFile ) { // update the process cache...
803 $this->expensiveCache
->set( $path, 'localRef',
804 [ 'object' => $fsFile, 'latest' => $latest ] );
812 * @see FileBackendStore::getLocalReferenceMulti()
813 * @param array $params
816 protected function doGetLocalReferenceMulti( array $params ) {
817 return $this->doGetLocalCopyMulti( $params );
820 final public function getLocalCopyMulti( array $params ) {
821 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
823 $params = $this->setConcurrencyFlags( $params );
824 $tmpFiles = $this->doGetLocalCopyMulti( $params );
830 * @see FileBackendStore::getLocalCopyMulti()
831 * @param array $params
834 abstract protected function doGetLocalCopyMulti( array $params );
837 * @see FileBackend::getFileHttpUrl()
838 * @param array $params
839 * @return string|null
841 public function getFileHttpUrl( array $params ) {
842 return null; // not supported
845 final public function streamFile( array $params ) {
846 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
847 $status = $this->newStatus();
849 // Always set some fields for subclass convenience
850 $params['options'] = isset( $params['options'] ) ?
$params['options'] : [];
851 $params['headers'] = isset( $params['headers'] ) ?
$params['headers'] : [];
853 // Don't stream it out as text/html if there was a PHP error
854 if ( ( empty( $params['headless'] ) ||
$params['headers'] ) && headers_sent() ) {
855 print "Headers already sent, terminating.\n";
856 $status->fatal( 'backend-fail-stream', $params['src'] );
860 $status->merge( $this->doStreamFile( $params ) );
866 * @see FileBackendStore::streamFile()
867 * @param array $params
868 * @return StatusValue
870 protected function doStreamFile( array $params ) {
871 $status = $this->newStatus();
874 $flags |
= !empty( $params['headless'] ) ? HTTPFileStreamer
::STREAM_HEADLESS
: 0;
875 $flags |
= !empty( $params['allowOB'] ) ? HTTPFileStreamer
::STREAM_ALLOW_OB
: 0;
877 $fsFile = $this->getLocalReference( $params );
879 $streamer = new HTTPFileStreamer(
882 'obResetFunc' => $this->obResetFunc
,
883 'streamMimeFunc' => $this->streamMimeFunc
886 $res = $streamer->stream( $params['headers'], true, $params['options'], $flags );
889 HTTPFileStreamer
::send404Message( $params['src'], $flags );
893 $status->fatal( 'backend-fail-stream', $params['src'] );
899 final public function directoryExists( array $params ) {
900 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
901 if ( $dir === null ) {
902 return false; // invalid storage path
904 if ( $shard !== null ) { // confined to a single container/shard
905 return $this->doDirectoryExists( $fullCont, $dir, $params );
906 } else { // directory is on several shards
907 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
908 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
909 $res = false; // response
910 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
911 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
915 } elseif ( $exists === null ) { // error?
916 $res = null; // if we don't find anything, it is indeterminate
925 * @see FileBackendStore::directoryExists()
927 * @param string $container Resolved container name
928 * @param string $dir Resolved path relative to container
929 * @param array $params
932 abstract protected function doDirectoryExists( $container, $dir, array $params );
934 final public function getDirectoryList( array $params ) {
935 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
936 if ( $dir === null ) { // invalid storage path
939 if ( $shard !== null ) {
940 // File listing is confined to a single container/shard
941 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
943 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
944 // File listing spans multiple containers/shards
945 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
947 return new FileBackendStoreShardDirIterator( $this,
948 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
953 * Do not call this function from places outside FileBackend
955 * @see FileBackendStore::getDirectoryList()
957 * @param string $container Resolved container name
958 * @param string $dir Resolved path relative to container
959 * @param array $params
960 * @return Traversable|array|null Returns null on failure
962 abstract public function getDirectoryListInternal( $container, $dir, array $params );
964 final public function getFileList( array $params ) {
965 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
966 if ( $dir === null ) { // invalid storage path
969 if ( $shard !== null ) {
970 // File listing is confined to a single container/shard
971 return $this->getFileListInternal( $fullCont, $dir, $params );
973 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
974 // File listing spans multiple containers/shards
975 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
977 return new FileBackendStoreShardFileIterator( $this,
978 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
983 * Do not call this function from places outside FileBackend
985 * @see FileBackendStore::getFileList()
987 * @param string $container Resolved container name
988 * @param string $dir Resolved path relative to container
989 * @param array $params
990 * @return Traversable|array|null Returns null on failure
992 abstract public function getFileListInternal( $container, $dir, array $params );
995 * Return a list of FileOp objects from a list of operations.
996 * Do not call this function from places outside FileBackend.
998 * The result must have the same number of items as the input.
999 * An exception is thrown if an unsupported operation is requested.
1001 * @param array $ops Same format as doOperations()
1002 * @return FileOp[] List of FileOp objects
1003 * @throws FileBackendError
1005 final public function getOperationsInternal( array $ops ) {
1007 'store' => 'StoreFileOp',
1008 'copy' => 'CopyFileOp',
1009 'move' => 'MoveFileOp',
1010 'delete' => 'DeleteFileOp',
1011 'create' => 'CreateFileOp',
1012 'describe' => 'DescribeFileOp',
1013 'null' => 'NullFileOp'
1016 $performOps = []; // array of FileOp objects
1017 // Build up ordered array of FileOps...
1018 foreach ( $ops as $operation ) {
1019 $opName = $operation['op'];
1020 if ( isset( $supportedOps[$opName] ) ) {
1021 $class = $supportedOps[$opName];
1022 // Get params for this operation
1023 $params = $operation;
1024 // Append the FileOp class
1025 $performOps[] = new $class( $this, $params, $this->logger
);
1027 throw new FileBackendError( "Operation '$opName' is not supported." );
1035 * Get a list of storage paths to lock for a list of operations
1036 * Returns an array with LockManager::LOCK_UW (shared locks) and
1037 * LockManager::LOCK_EX (exclusive locks) keys, each corresponding
1038 * to a list of storage paths to be locked. All returned paths are
1041 * @param array $performOps List of FileOp objects
1042 * @return array (LockManager::LOCK_UW => path list, LockManager::LOCK_EX => path list)
1044 final public function getPathsToLockForOpsInternal( array $performOps ) {
1045 // Build up a list of files to lock...
1046 $paths = [ 'sh' => [], 'ex' => [] ];
1047 foreach ( $performOps as $fileOp ) {
1048 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1049 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1051 // Optimization: if doing an EX lock anyway, don't also set an SH one
1052 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1053 // Get a shared lock on the parent directory of each path changed
1054 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1057 LockManager
::LOCK_UW
=> $paths['sh'],
1058 LockManager
::LOCK_EX
=> $paths['ex']
1062 public function getScopedLocksForOps( array $ops, StatusValue
$status ) {
1063 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1065 return $this->getScopedFileLocks( $paths, 'mixed', $status );
1068 final protected function doOperationsInternal( array $ops, array $opts ) {
1069 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1070 $status = $this->newStatus();
1072 // Fix up custom header name/value pairs...
1073 $ops = array_map( [ $this, 'sanitizeOpHeaders' ], $ops );
1075 // Build up a list of FileOps...
1076 $performOps = $this->getOperationsInternal( $ops );
1078 // Acquire any locks as needed...
1079 if ( empty( $opts['nonLocking'] ) ) {
1080 // Build up a list of files to lock...
1081 $paths = $this->getPathsToLockForOpsInternal( $performOps );
1082 // Try to lock those files for the scope of this function...
1084 $scopeLock = $this->getScopedFileLocks( $paths, 'mixed', $status );
1085 if ( !$status->isOK() ) {
1086 return $status; // abort
1090 // Clear any file cache entries (after locks acquired)
1091 if ( empty( $opts['preserveCache'] ) ) {
1092 $this->clearCache();
1095 // Build the list of paths involved
1097 foreach ( $performOps as $op ) {
1098 $paths = array_merge( $paths, $op->storagePathsRead() );
1099 $paths = array_merge( $paths, $op->storagePathsChanged() );
1102 // Enlarge the cache to fit the stat entries of these files
1103 $this->cheapCache
->resize( max( 2 * count( $paths ), self
::CACHE_CHEAP_SIZE
) );
1105 // Load from the persistent container caches
1106 $this->primeContainerCache( $paths );
1107 // Get the latest stat info for all the files (having locked them)
1108 $ok = $this->preloadFileStat( [ 'srcs' => $paths, 'latest' => true ] );
1111 // Actually attempt the operation batch...
1112 $opts = $this->setConcurrencyFlags( $opts );
1113 $subStatus = FileOpBatch
::attempt( $performOps, $opts, $this->fileJournal
);
1115 // If we could not even stat some files, then bail out...
1116 $subStatus = $this->newStatus( 'backend-fail-internal', $this->name
);
1117 foreach ( $ops as $i => $op ) { // mark each op as failed
1118 $subStatus->success
[$i] = false;
1119 ++
$subStatus->failCount
;
1121 $this->logger
->error( get_class( $this ) . "-{$this->name} " .
1122 " stat failure; aborted operations: " . FormatJson
::encode( $ops ) );
1125 // Merge errors into StatusValue fields
1126 $status->merge( $subStatus );
1127 $status->success
= $subStatus->success
; // not done in merge()
1129 // Shrink the stat cache back to normal size
1130 $this->cheapCache
->resize( self
::CACHE_CHEAP_SIZE
);
1135 final protected function doQuickOperationsInternal( array $ops ) {
1136 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1137 $status = $this->newStatus();
1139 // Fix up custom header name/value pairs...
1140 $ops = array_map( [ $this, 'sanitizeOpHeaders' ], $ops );
1142 // Clear any file cache entries
1143 $this->clearCache();
1145 $supportedOps = [ 'create', 'store', 'copy', 'move', 'delete', 'describe', 'null' ];
1146 // Parallel ops may be disabled in config due to dependencies (e.g. needing popen())
1147 $async = ( $this->parallelize
=== 'implicit' && count( $ops ) > 1 );
1148 $maxConcurrency = $this->concurrency
; // throttle
1149 /** @var StatusValue[] $statuses */
1150 $statuses = []; // array of (index => StatusValue)
1151 $fileOpHandles = []; // list of (index => handle) arrays
1152 $curFileOpHandles = []; // current handle batch
1153 // Perform the sync-only ops and build up op handles for the async ops...
1154 foreach ( $ops as $index => $params ) {
1155 if ( !in_array( $params['op'], $supportedOps ) ) {
1156 throw new FileBackendError( "Operation '{$params['op']}' is not supported." );
1158 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1159 $subStatus = $this->$method( [ 'async' => $async ] +
$params );
1160 if ( $subStatus->value
instanceof FileBackendStoreOpHandle
) { // async
1161 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1162 $fileOpHandles[] = $curFileOpHandles; // push this batch
1163 $curFileOpHandles = [];
1165 $curFileOpHandles[$index] = $subStatus->value
; // keep index
1166 } else { // error or completed
1167 $statuses[$index] = $subStatus; // keep index
1170 if ( count( $curFileOpHandles ) ) {
1171 $fileOpHandles[] = $curFileOpHandles; // last batch
1173 // Do all the async ops that can be done concurrently...
1174 foreach ( $fileOpHandles as $fileHandleBatch ) {
1175 $statuses = $statuses +
$this->executeOpHandlesInternal( $fileHandleBatch );
1177 // Marshall and merge all the responses...
1178 foreach ( $statuses as $index => $subStatus ) {
1179 $status->merge( $subStatus );
1180 if ( $subStatus->isOK() ) {
1181 $status->success
[$index] = true;
1182 ++
$status->successCount
;
1184 $status->success
[$index] = false;
1185 ++
$status->failCount
;
1193 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1194 * The resulting StatusValue object fields will correspond
1195 * to the order in which the handles where given.
1197 * @param FileBackendStoreOpHandle[] $fileOpHandles
1199 * @throws FileBackendError
1200 * @return StatusValue[] Map of StatusValue objects
1202 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1203 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1205 foreach ( $fileOpHandles as $fileOpHandle ) {
1206 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle
) ) {
1207 throw new InvalidArgumentException( "Got a non-FileBackendStoreOpHandle object." );
1208 } elseif ( $fileOpHandle->backend
->getName() !== $this->getName() ) {
1209 throw new InvalidArgumentException(
1210 "Got a FileBackendStoreOpHandle for the wrong backend." );
1213 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1214 foreach ( $fileOpHandles as $fileOpHandle ) {
1215 $fileOpHandle->closeResources();
1222 * @see FileBackendStore::executeOpHandlesInternal()
1224 * @param FileBackendStoreOpHandle[] $fileOpHandles
1226 * @throws FileBackendError
1227 * @return StatusValue[] List of corresponding StatusValue objects
1229 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1230 if ( count( $fileOpHandles ) ) {
1231 throw new LogicException( "Backend does not support asynchronous operations." );
1238 * Normalize and filter HTTP headers from a file operation
1240 * This normalizes and strips long HTTP headers from a file operation.
1241 * Most headers are just numbers, but some are allowed to be long.
1242 * This function is useful for cleaning up headers and avoiding backend
1243 * specific errors, especially in the middle of batch file operations.
1245 * @param array $op Same format as doOperation()
1248 protected function sanitizeOpHeaders( array $op ) {
1249 static $longs = [ 'content-disposition' ];
1251 if ( isset( $op['headers'] ) ) { // op sets HTTP headers
1253 foreach ( $op['headers'] as $name => $value ) {
1254 $name = strtolower( $name );
1255 $maxHVLen = in_array( $name, $longs ) ? INF
: 255;
1256 if ( strlen( $name ) > 255 ||
strlen( $value ) > $maxHVLen ) {
1257 trigger_error( "Header '$name: $value' is too long." );
1259 $newHeaders[$name] = strlen( $value ) ?
$value : ''; // null/false => ""
1262 $op['headers'] = $newHeaders;
1268 final public function preloadCache( array $paths ) {
1269 $fullConts = []; // full container names
1270 foreach ( $paths as $path ) {
1271 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1272 $fullConts[] = $fullCont;
1274 // Load from the persistent file and container caches
1275 $this->primeContainerCache( $fullConts );
1276 $this->primeFileCache( $paths );
1279 final public function clearCache( array $paths = null ) {
1280 if ( is_array( $paths ) ) {
1281 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1282 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1284 if ( $paths === null ) {
1285 $this->cheapCache
->clear();
1286 $this->expensiveCache
->clear();
1288 foreach ( $paths as $path ) {
1289 $this->cheapCache
->clear( $path );
1290 $this->expensiveCache
->clear( $path );
1293 $this->doClearCache( $paths );
1297 * Clears any additional stat caches for storage paths
1299 * @see FileBackend::clearCache()
1301 * @param array $paths Storage paths (optional)
1303 protected function doClearCache( array $paths = null ) {
1306 final public function preloadFileStat( array $params ) {
1307 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1308 $success = true; // no network errors
1310 $params['concurrency'] = ( $this->parallelize
!== 'off' ) ?
$this->concurrency
: 1;
1311 $stats = $this->doGetFileStatMulti( $params );
1312 if ( $stats === null ) {
1313 return true; // not supported
1316 $latest = !empty( $params['latest'] ); // use latest data?
1317 foreach ( $stats as $path => $stat ) {
1318 $path = FileBackend
::normalizeStoragePath( $path );
1319 if ( $path === null ) {
1320 continue; // this shouldn't happen
1322 if ( is_array( $stat ) ) { // file exists
1323 // Strongly consistent backends can automatically set "latest"
1324 $stat['latest'] = isset( $stat['latest'] ) ?
$stat['latest'] : $latest;
1325 $this->cheapCache
->set( $path, 'stat', $stat );
1326 $this->setFileCache( $path, $stat ); // update persistent cache
1327 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
1328 $this->cheapCache
->set( $path, 'sha1',
1329 [ 'hash' => $stat['sha1'], 'latest' => $latest ] );
1331 if ( isset( $stat['xattr'] ) ) { // some backends store headers/metadata
1332 $stat['xattr'] = self
::normalizeXAttributes( $stat['xattr'] );
1333 $this->cheapCache
->set( $path, 'xattr',
1334 [ 'map' => $stat['xattr'], 'latest' => $latest ] );
1336 } elseif ( $stat === false ) { // file does not exist
1337 $this->cheapCache
->set( $path, 'stat',
1338 $latest ?
'NOT_EXIST_LATEST' : 'NOT_EXIST' );
1339 $this->cheapCache
->set( $path, 'xattr',
1340 [ 'map' => false, 'latest' => $latest ] );
1341 $this->cheapCache
->set( $path, 'sha1',
1342 [ 'hash' => false, 'latest' => $latest ] );
1343 $this->logger
->debug( __METHOD__
. ": File $path does not exist.\n" );
1344 } else { // an error occurred
1346 $this->logger
->warning( __METHOD__
. ": Could not stat file $path.\n" );
1354 * Get file stat information (concurrently if possible) for several files
1356 * @see FileBackend::getFileStat()
1358 * @param array $params Parameters include:
1359 * - srcs : list of source storage paths
1360 * - latest : use the latest available data
1361 * @return array|null Map of storage paths to array|bool|null (returns null if not supported)
1364 protected function doGetFileStatMulti( array $params ) {
1365 return null; // not supported
1369 * Is this a key/value store where directories are just virtual?
1370 * Virtual directories exists in so much as files exists that are
1371 * prefixed with the directory path followed by a forward slash.
1375 abstract protected function directoriesAreVirtual();
1378 * Check if a short container name is valid
1380 * This checks for length and illegal characters.
1381 * This may disallow certain characters that can appear
1382 * in the prefix used to make the full container name.
1384 * @param string $container
1387 final protected static function isValidShortContainerName( $container ) {
1388 // Suffixes like '.xxx' (hex shard chars) or '.seg' (file segments)
1389 // might be used by subclasses. Reserve the dot character for sanity.
1390 // The only way dots end up in containers (e.g. resolveStoragePath)
1391 // is due to the wikiId container prefix or the above suffixes.
1392 return self
::isValidContainerName( $container ) && !preg_match( '/[.]/', $container );
1396 * Check if a full container name is valid
1398 * This checks for length and illegal characters.
1399 * Limiting the characters makes migrations to other stores easier.
1401 * @param string $container
1404 final protected static function isValidContainerName( $container ) {
1405 // This accounts for NTFS, Swift, and Ceph restrictions
1406 // and disallows directory separators or traversal characters.
1407 // Note that matching strings URL encode to the same string;
1408 // in Swift/Ceph, the length restriction is *after* URL encoding.
1409 return (bool)preg_match( '/^[a-z0-9][a-z0-9-_.]{0,199}$/i', $container );
1413 * Splits a storage path into an internal container name,
1414 * an internal relative file name, and a container shard suffix.
1415 * Any shard suffix is already appended to the internal container name.
1416 * This also checks that the storage path is valid and within this backend.
1418 * If the container is sharded but a suffix could not be determined,
1419 * this means that the path can only refer to a directory and can only
1420 * be scanned by looking in all the container shards.
1422 * @param string $storagePath
1423 * @return array (container, path, container suffix) or (null, null, null) if invalid
1425 final protected function resolveStoragePath( $storagePath ) {
1426 list( $backend, $shortCont, $relPath ) = self
::splitStoragePath( $storagePath );
1427 if ( $backend === $this->name
) { // must be for this backend
1428 $relPath = self
::normalizeContainerPath( $relPath );
1429 if ( $relPath !== null && self
::isValidShortContainerName( $shortCont ) ) {
1430 // Get shard for the normalized path if this container is sharded
1431 $cShard = $this->getContainerShard( $shortCont, $relPath );
1432 // Validate and sanitize the relative path (backend-specific)
1433 $relPath = $this->resolveContainerPath( $shortCont, $relPath );
1434 if ( $relPath !== null ) {
1435 // Prepend any wiki ID prefix to the container name
1436 $container = $this->fullContainerName( $shortCont );
1437 if ( self
::isValidContainerName( $container ) ) {
1438 // Validate and sanitize the container name (backend-specific)
1439 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1440 if ( $container !== null ) {
1441 return [ $container, $relPath, $cShard ];
1448 return [ null, null, null ];
1452 * Like resolveStoragePath() except null values are returned if
1453 * the container is sharded and the shard could not be determined
1454 * or if the path ends with '/'. The latter case is illegal for FS
1455 * backends and can confuse listings for object store backends.
1457 * This function is used when resolving paths that must be valid
1458 * locations for files. Directory and listing functions should
1459 * generally just use resolveStoragePath() instead.
1461 * @see FileBackendStore::resolveStoragePath()
1463 * @param string $storagePath
1464 * @return array (container, path) or (null, null) if invalid
1466 final protected function resolveStoragePathReal( $storagePath ) {
1467 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1468 if ( $cShard !== null && substr( $relPath, -1 ) !== '/' ) {
1469 return [ $container, $relPath ];
1472 return [ null, null ];
1476 * Get the container name shard suffix for a given path.
1477 * Any empty suffix means the container is not sharded.
1479 * @param string $container Container name
1480 * @param string $relPath Storage path relative to the container
1481 * @return string|null Returns null if shard could not be determined
1483 final protected function getContainerShard( $container, $relPath ) {
1484 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1485 if ( $levels == 1 ||
$levels == 2 ) {
1486 // Hash characters are either base 16 or 36
1487 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1488 // Get a regex that represents the shard portion of paths.
1489 // The concatenation of the captures gives us the shard.
1490 if ( $levels === 1 ) { // 16 or 36 shards per container
1491 $hashDirRegex = '(' . $char . ')';
1492 } else { // 256 or 1296 shards per container
1493 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1494 $hashDirRegex = $char . '/(' . $char . '{2})';
1495 } else { // short hash dir format (e.g. "a/b/c")
1496 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1499 // Allow certain directories to be above the hash dirs so as
1500 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1501 // They must be 2+ chars to avoid any hash directory ambiguity.
1503 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1504 return '.' . implode( '', array_slice( $m, 1 ) );
1507 return null; // failed to match
1510 return ''; // no sharding
1514 * Check if a storage path maps to a single shard.
1515 * Container dirs like "a", where the container shards on "x/xy",
1516 * can reside on several shards. Such paths are tricky to handle.
1518 * @param string $storagePath Storage path
1521 final public function isSingleShardPathInternal( $storagePath ) {
1522 list( , , $shard ) = $this->resolveStoragePath( $storagePath );
1524 return ( $shard !== null );
1528 * Get the sharding config for a container.
1529 * If greater than 0, then all file storage paths within
1530 * the container are required to be hashed accordingly.
1532 * @param string $container
1533 * @return array (integer levels, integer base, repeat flag) or (0, 0, false)
1535 final protected function getContainerHashLevels( $container ) {
1536 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1537 $config = $this->shardViaHashLevels
[$container];
1538 $hashLevels = (int)$config['levels'];
1539 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1540 $hashBase = (int)$config['base'];
1541 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1542 return [ $hashLevels, $hashBase, $config['repeat'] ];
1547 return [ 0, 0, false ]; // no sharding
1551 * Get a list of full container shard suffixes for a container
1553 * @param string $container
1556 final protected function getContainerSuffixes( $container ) {
1558 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1559 if ( $digits > 0 ) {
1560 $numShards = pow( $base, $digits );
1561 for ( $index = 0; $index < $numShards; $index++
) {
1562 $shards[] = '.' . Wikimedia\base_convert
( $index, 10, $base, $digits );
1570 * Get the full container name, including the wiki ID prefix
1572 * @param string $container
1575 final protected function fullContainerName( $container ) {
1576 if ( $this->domainId
!= '' ) {
1577 return "{$this->domainId}-$container";
1584 * Resolve a container name, checking if it's allowed by the backend.
1585 * This is intended for internal use, such as encoding illegal chars.
1586 * Subclasses can override this to be more restrictive.
1588 * @param string $container
1589 * @return string|null
1591 protected function resolveContainerName( $container ) {
1596 * Resolve a relative storage path, checking if it's allowed by the backend.
1597 * This is intended for internal use, such as encoding illegal chars or perhaps
1598 * getting absolute paths (e.g. FS based backends). Note that the relative path
1599 * may be the empty string (e.g. the path is simply to the container).
1601 * @param string $container Container name
1602 * @param string $relStoragePath Storage path relative to the container
1603 * @return string|null Path or null if not valid
1605 protected function resolveContainerPath( $container, $relStoragePath ) {
1606 return $relStoragePath;
1610 * Get the cache key for a container
1612 * @param string $container Resolved container name
1615 private function containerCacheKey( $container ) {
1616 return "filebackend:{$this->name}:{$this->domainId}:container:{$container}";
1620 * Set the cached info for a container
1622 * @param string $container Resolved container name
1623 * @param array $val Information to cache
1625 final protected function setContainerCache( $container, array $val ) {
1626 $this->memCache
->set( $this->containerCacheKey( $container ), $val, 14 * 86400 );
1630 * Delete the cached info for a container.
1631 * The cache key is salted for a while to prevent race conditions.
1633 * @param string $container Resolved container name
1635 final protected function deleteContainerCache( $container ) {
1636 if ( !$this->memCache
->delete( $this->containerCacheKey( $container ), 300 ) ) {
1637 trigger_error( "Unable to delete stat cache for container $container." );
1642 * Do a batch lookup from cache for container stats for all containers
1643 * used in a list of container names or storage paths objects.
1644 * This loads the persistent cache values into the process cache.
1646 * @param array $items
1648 final protected function primeContainerCache( array $items ) {
1649 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1651 $paths = []; // list of storage paths
1652 $contNames = []; // (cache key => resolved container name)
1653 // Get all the paths/containers from the items...
1654 foreach ( $items as $item ) {
1655 if ( self
::isStoragePath( $item ) ) {
1657 } elseif ( is_string( $item ) ) { // full container name
1658 $contNames[$this->containerCacheKey( $item )] = $item;
1661 // Get all the corresponding cache keys for paths...
1662 foreach ( $paths as $path ) {
1663 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1664 if ( $fullCont !== null ) { // valid path for this backend
1665 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1669 $contInfo = []; // (resolved container name => cache value)
1670 // Get all cache entries for these container cache keys...
1671 $values = $this->memCache
->getMulti( array_keys( $contNames ) );
1672 foreach ( $values as $cacheKey => $val ) {
1673 $contInfo[$contNames[$cacheKey]] = $val;
1676 // Populate the container process cache for the backend...
1677 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1681 * Fill the backend-specific process cache given an array of
1682 * resolved container names and their corresponding cached info.
1683 * Only containers that actually exist should appear in the map.
1685 * @param array $containerInfo Map of resolved container names to cached info
1687 protected function doPrimeContainerCache( array $containerInfo ) {
1691 * Get the cache key for a file path
1693 * @param string $path Normalized storage path
1696 private function fileCacheKey( $path ) {
1697 return "filebackend:{$this->name}:{$this->domainId}:file:" . sha1( $path );
1701 * Set the cached stat info for a file path.
1702 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1703 * salting for the case when a file is created at a path were there was none before.
1705 * @param string $path Storage path
1706 * @param array $val Stat information to cache
1708 final protected function setFileCache( $path, array $val ) {
1709 $path = FileBackend
::normalizeStoragePath( $path );
1710 if ( $path === null ) {
1711 return; // invalid storage path
1713 $mtime = ConvertibleTimestamp
::convert( TS_UNIX
, $val['mtime'] );
1714 $ttl = $this->memCache
->adaptiveTTL( $mtime, 7 * 86400, 300, .1 );
1715 $key = $this->fileCacheKey( $path );
1716 // Set the cache unless it is currently salted.
1717 $this->memCache
->set( $key, $val, $ttl );
1721 * Delete the cached stat info for a file path.
1722 * The cache key is salted for a while to prevent race conditions.
1723 * Since negatives (404s) are not cached, this does not need to be called when
1724 * a file is created at a path were there was none before.
1726 * @param string $path Storage path
1728 final protected function deleteFileCache( $path ) {
1729 $path = FileBackend
::normalizeStoragePath( $path );
1730 if ( $path === null ) {
1731 return; // invalid storage path
1733 if ( !$this->memCache
->delete( $this->fileCacheKey( $path ), 300 ) ) {
1734 trigger_error( "Unable to delete stat cache for file $path." );
1739 * Do a batch lookup from cache for file stats for all paths
1740 * used in a list of storage paths or FileOp objects.
1741 * This loads the persistent cache values into the process cache.
1743 * @param array $items List of storage paths
1745 final protected function primeFileCache( array $items ) {
1746 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1748 $paths = []; // list of storage paths
1749 $pathNames = []; // (cache key => storage path)
1750 // Get all the paths/containers from the items...
1751 foreach ( $items as $item ) {
1752 if ( self
::isStoragePath( $item ) ) {
1753 $paths[] = FileBackend
::normalizeStoragePath( $item );
1756 // Get rid of any paths that failed normalization...
1757 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1758 // Get all the corresponding cache keys for paths...
1759 foreach ( $paths as $path ) {
1760 list( , $rel, ) = $this->resolveStoragePath( $path );
1761 if ( $rel !== null ) { // valid path for this backend
1762 $pathNames[$this->fileCacheKey( $path )] = $path;
1765 // Get all cache entries for these file cache keys...
1766 $values = $this->memCache
->getMulti( array_keys( $pathNames ) );
1767 foreach ( $values as $cacheKey => $val ) {
1768 $path = $pathNames[$cacheKey];
1769 if ( is_array( $val ) ) {
1770 $val['latest'] = false; // never completely trust cache
1771 $this->cheapCache
->set( $path, 'stat', $val );
1772 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1773 $this->cheapCache
->set( $path, 'sha1',
1774 [ 'hash' => $val['sha1'], 'latest' => false ] );
1776 if ( isset( $val['xattr'] ) ) { // some backends store headers/metadata
1777 $val['xattr'] = self
::normalizeXAttributes( $val['xattr'] );
1778 $this->cheapCache
->set( $path, 'xattr',
1779 [ 'map' => $val['xattr'], 'latest' => false ] );
1786 * Normalize file headers/metadata to the FileBackend::getFileXAttributes() format
1788 * @param array $xattr
1792 final protected static function normalizeXAttributes( array $xattr ) {
1793 $newXAttr = [ 'headers' => [], 'metadata' => [] ];
1795 foreach ( $xattr['headers'] as $name => $value ) {
1796 $newXAttr['headers'][strtolower( $name )] = $value;
1799 foreach ( $xattr['metadata'] as $name => $value ) {
1800 $newXAttr['metadata'][strtolower( $name )] = $value;
1807 * Set the 'concurrency' option from a list of operation options
1809 * @param array $opts Map of operation options
1812 final protected function setConcurrencyFlags( array $opts ) {
1813 $opts['concurrency'] = 1; // off
1814 if ( $this->parallelize
=== 'implicit' ) {
1815 if ( !isset( $opts['parallelize'] ) ||
$opts['parallelize'] ) {
1816 $opts['concurrency'] = $this->concurrency
;
1818 } elseif ( $this->parallelize
=== 'explicit' ) {
1819 if ( !empty( $opts['parallelize'] ) ) {
1820 $opts['concurrency'] = $this->concurrency
;
1828 * Get the content type to use in HEAD/GET requests for a file
1830 * @param string $storagePath
1831 * @param string|null $content File data
1832 * @param string|null $fsPath File system path
1833 * @return string MIME type
1835 protected function getContentType( $storagePath, $content, $fsPath ) {
1836 if ( $this->mimeCallback
) {
1837 return call_user_func_array( $this->mimeCallback
, func_get_args() );
1841 if ( $fsPath !== null && function_exists( 'finfo_file' ) ) {
1842 $finfo = finfo_open( FILEINFO_MIME_TYPE
);
1843 $mime = finfo_file( $finfo, $fsPath );
1844 finfo_close( $finfo );
1847 return is_string( $mime ) ?
$mime : 'unknown/unknown';
1852 * FileBackendStore helper class for performing asynchronous file operations.
1854 * For example, calling FileBackendStore::createInternal() with the "async"
1855 * param flag may result in a StatusValue that contains this object as a value.
1856 * This class is largely backend-specific and is mostly just "magic" to be
1857 * passed to FileBackendStore::executeOpHandlesInternal().
1859 abstract class FileBackendStoreOpHandle
{
1861 public $params = []; // params to caller functions
1862 /** @var FileBackendStore */
1865 public $resourcesToClose = [];
1867 public $call; // string; name that identifies the function called
1870 * Close all open file handles
1872 public function closeResources() {
1873 array_map( 'fclose', $this->resourcesToClose
);
1878 * FileBackendStore helper function to handle listings that span container shards.
1879 * Do not use this class from places outside of FileBackendStore.
1881 * @ingroup FileBackend
1883 abstract class FileBackendStoreShardListIterator
extends FilterIterator
{
1884 /** @var FileBackendStore */
1890 /** @var string Full container name */
1891 protected $container;
1893 /** @var string Resolved relative path */
1894 protected $directory;
1897 protected $multiShardPaths = []; // (rel path => 1)
1900 * @param FileBackendStore $backend
1901 * @param string $container Full storage container name
1902 * @param string $dir Storage directory relative to container
1903 * @param array $suffixes List of container shard suffixes
1904 * @param array $params
1906 public function __construct(
1907 FileBackendStore
$backend, $container, $dir, array $suffixes, array $params
1909 $this->backend
= $backend;
1910 $this->container
= $container;
1911 $this->directory
= $dir;
1912 $this->params
= $params;
1914 $iter = new AppendIterator();
1915 foreach ( $suffixes as $suffix ) {
1916 $iter->append( $this->listFromShard( $this->container
. $suffix ) );
1919 parent
::__construct( $iter );
1922 public function accept() {
1923 $rel = $this->getInnerIterator()->current(); // path relative to given directory
1924 $path = $this->params
['dir'] . "/{$rel}"; // full storage path
1925 if ( $this->backend
->isSingleShardPathInternal( $path ) ) {
1926 return true; // path is only on one shard; no issue with duplicates
1927 } elseif ( isset( $this->multiShardPaths
[$rel] ) ) {
1928 // Don't keep listing paths that are on multiple shards
1931 $this->multiShardPaths
[$rel] = 1;
1937 public function rewind() {
1939 $this->multiShardPaths
= [];
1943 * Get the list for a given container shard
1945 * @param string $container Resolved container name
1948 abstract protected function listFromShard( $container );
1952 * Iterator for listing directories
1954 class FileBackendStoreShardDirIterator
extends FileBackendStoreShardListIterator
{
1955 protected function listFromShard( $container ) {
1956 $list = $this->backend
->getDirectoryListInternal(
1957 $container, $this->directory
, $this->params
);
1958 if ( $list === null ) {
1959 return new ArrayIterator( [] );
1961 return is_array( $list ) ?
new ArrayIterator( $list ) : $list;
1967 * Iterator for listing regular files
1969 class FileBackendStoreShardFileIterator
extends FileBackendStoreShardListIterator
{
1970 protected function listFromShard( $container ) {
1971 $list = $this->backend
->getFileListInternal(
1972 $container, $this->directory
, $this->params
);
1973 if ( $list === null ) {
1974 return new ArrayIterator( [] );
1976 return is_array( $list ) ?
new ArrayIterator( $list ) : $list;