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
23 use Wikimedia\Timestamp\ConvertibleTimestamp
;
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 */
43 /** @var MapCacheLRU Map of paths to small (RAM/disk) cache items */
44 protected $cheapCache;
45 /** @var MapCacheLRU Map of paths to large (RAM/disk) cache items */
46 protected $expensiveCache;
48 /** @var array Map of container names to sharding config */
49 protected $shardViaHashLevels = [];
51 /** @var callable Method to get the MIME type of files */
52 protected $mimeCallback;
54 protected $maxFileSize = 4294967296; // integer bytes (4GiB)
56 const CACHE_TTL
= 10; // integer; TTL in seconds for process cache entries
57 const CACHE_CHEAP_SIZE
= 500; // integer; max entries in "cheap cache"
58 const CACHE_EXPENSIVE_SIZE
= 5; // integer; max entries in "expensive cache"
61 * @see FileBackend::__construct()
62 * Additional $config params include:
63 * - srvCache : BagOStuff cache to APC or the like.
64 * - wanCache : WANObjectCache object to use for persistent caching.
65 * - mimeCallback : Callback that takes (storage path, content, file system path) and
66 * returns the MIME type of the file or 'unknown/unknown'. The file
67 * system path parameter should be used if the content one is null.
69 * @param array $config
71 public function __construct( array $config ) {
72 parent
::__construct( $config );
73 $this->mimeCallback
= $config['mimeCallback'] ??
null;
74 $this->srvCache
= new EmptyBagOStuff(); // disabled by default
75 $this->memCache
= WANObjectCache
::newEmpty(); // disabled by default
76 $this->cheapCache
= new MapCacheLRU( self
::CACHE_CHEAP_SIZE
);
77 $this->expensiveCache
= new MapCacheLRU( self
::CACHE_EXPENSIVE_SIZE
);
81 * Get the maximum allowable file size given backend
82 * medium restrictions and basic performance constraints.
83 * Do not call this function from places outside FileBackend and FileOp.
87 final public function maxFileSizeInternal() {
88 return $this->maxFileSize
;
92 * Check if a file can be created or changed at a given storage path.
93 * FS backends should check if the parent directory exists, files can be
94 * written under it, and that any file already there is writable.
95 * Backends using key/value stores should check if the container exists.
97 * @param string $storagePath
100 abstract public function isPathUsableInternal( $storagePath );
103 * Create a file in the backend with the given contents.
104 * This will overwrite any file that exists at the destination.
105 * Do not call this function from places outside FileBackend and FileOp.
108 * - content : the raw file contents
109 * - dst : destination storage path
110 * - headers : HTTP header name/value map
111 * - async : StatusValue will be returned immediately if supported.
112 * If the StatusValue is OK, then its value field will be
113 * set to a FileBackendStoreOpHandle object.
114 * - dstExists : Whether a file exists at the destination (optimization).
115 * Callers can use "false" if no existing file is being changed.
117 * @param array $params
118 * @return StatusValue
120 final public function createInternal( array $params ) {
121 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
122 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
123 $status = $this->newStatus( 'backend-fail-maxsize',
124 $params['dst'], $this->maxFileSizeInternal() );
126 $status = $this->doCreateInternal( $params );
127 $this->clearCache( [ $params['dst'] ] );
128 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
129 $this->deleteFileCache( $params['dst'] ); // persistent cache
137 * @see FileBackendStore::createInternal()
138 * @param array $params
139 * @return StatusValue
141 abstract protected function doCreateInternal( array $params );
144 * Store a file into the backend from a file on disk.
145 * This will overwrite any file that exists at the destination.
146 * Do not call this function from places outside FileBackend and FileOp.
149 * - src : source path on disk
150 * - dst : destination storage path
151 * - headers : HTTP header name/value map
152 * - async : StatusValue will be returned immediately if supported.
153 * If the StatusValue is OK, then its value field will be
154 * set to a FileBackendStoreOpHandle object.
155 * - dstExists : Whether a file exists at the destination (optimization).
156 * Callers can use "false" if no existing file is being changed.
158 * @param array $params
159 * @return StatusValue
161 final public function storeInternal( array $params ) {
162 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
163 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
164 $status = $this->newStatus( 'backend-fail-maxsize',
165 $params['dst'], $this->maxFileSizeInternal() );
167 $status = $this->doStoreInternal( $params );
168 $this->clearCache( [ $params['dst'] ] );
169 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
170 $this->deleteFileCache( $params['dst'] ); // persistent cache
178 * @see FileBackendStore::storeInternal()
179 * @param array $params
180 * @return StatusValue
182 abstract protected function doStoreInternal( array $params );
185 * Copy a file from one storage path to another in the backend.
186 * This will overwrite any file that exists at the destination.
187 * Do not call this function from places outside FileBackend and FileOp.
190 * - src : source storage path
191 * - dst : destination storage path
192 * - ignoreMissingSource : do nothing if the source file does not exist
193 * - headers : HTTP header name/value map
194 * - async : StatusValue will be returned immediately if supported.
195 * If the StatusValue is OK, then its value field will be
196 * set to a FileBackendStoreOpHandle object.
197 * - dstExists : Whether a file exists at the destination (optimization).
198 * Callers can use "false" if no existing file is being changed.
200 * @param array $params
201 * @return StatusValue
203 final public function copyInternal( array $params ) {
204 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
205 $status = $this->doCopyInternal( $params );
206 $this->clearCache( [ $params['dst'] ] );
207 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
208 $this->deleteFileCache( $params['dst'] ); // persistent cache
215 * @see FileBackendStore::copyInternal()
216 * @param array $params
217 * @return StatusValue
219 abstract protected function doCopyInternal( array $params );
222 * Delete a file at the storage path.
223 * Do not call this function from places outside FileBackend and FileOp.
226 * - src : source storage path
227 * - ignoreMissingSource : do nothing if the source file does not exist
228 * - async : StatusValue will be returned immediately if supported.
229 * If the StatusValue is OK, then its value field will be
230 * set to a FileBackendStoreOpHandle object.
232 * @param array $params
233 * @return StatusValue
235 final public function deleteInternal( array $params ) {
236 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
237 $status = $this->doDeleteInternal( $params );
238 $this->clearCache( [ $params['src'] ] );
239 $this->deleteFileCache( $params['src'] ); // persistent cache
244 * @see FileBackendStore::deleteInternal()
245 * @param array $params
246 * @return StatusValue
248 abstract protected function doDeleteInternal( array $params );
251 * Move a file from one storage path to another in the backend.
252 * This will overwrite any file that exists at the destination.
253 * Do not call this function from places outside FileBackend and FileOp.
256 * - src : source storage path
257 * - dst : destination storage path
258 * - ignoreMissingSource : do nothing if the source file does not exist
259 * - headers : HTTP header name/value map
260 * - async : StatusValue will be returned immediately if supported.
261 * If the StatusValue is OK, then its value field will be
262 * set to a FileBackendStoreOpHandle object.
263 * - dstExists : Whether a file exists at the destination (optimization).
264 * Callers can use "false" if no existing file is being changed.
266 * @param array $params
267 * @return StatusValue
269 final public function moveInternal( array $params ) {
270 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
271 $status = $this->doMoveInternal( $params );
272 $this->clearCache( [ $params['src'], $params['dst'] ] );
273 $this->deleteFileCache( $params['src'] ); // persistent cache
274 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
275 $this->deleteFileCache( $params['dst'] ); // persistent cache
282 * @see FileBackendStore::moveInternal()
283 * @param array $params
284 * @return StatusValue
286 protected function doMoveInternal( array $params ) {
287 unset( $params['async'] ); // two steps, won't work here :)
288 $nsrc = FileBackend
::normalizeStoragePath( $params['src'] );
289 $ndst = FileBackend
::normalizeStoragePath( $params['dst'] );
290 // Copy source to dest
291 $status = $this->copyInternal( $params );
292 if ( $nsrc !== $ndst && $status->isOK() ) {
293 // Delete source (only fails due to races or network problems)
294 $status->merge( $this->deleteInternal( [ 'src' => $params['src'] ] ) );
295 $status->setResult( true, $status->value
); // ignore delete() errors
302 * Alter metadata for a file at the storage path.
303 * Do not call this function from places outside FileBackend and FileOp.
306 * - src : source storage path
307 * - headers : HTTP header name/value map
308 * - async : StatusValue will be returned immediately if supported.
309 * If the StatusValue is OK, then its value field will be
310 * set to a FileBackendStoreOpHandle object.
312 * @param array $params
313 * @return StatusValue
315 final public function describeInternal( array $params ) {
316 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
317 if ( count( $params['headers'] ) ) {
318 $status = $this->doDescribeInternal( $params );
319 $this->clearCache( [ $params['src'] ] );
320 $this->deleteFileCache( $params['src'] ); // persistent cache
322 $status = $this->newStatus(); // nothing to do
329 * @see FileBackendStore::describeInternal()
330 * @param array $params
331 * @return StatusValue
333 protected function doDescribeInternal( array $params ) {
334 return $this->newStatus();
338 * No-op file operation that does nothing.
339 * Do not call this function from places outside FileBackend and FileOp.
341 * @param array $params
342 * @return StatusValue
344 final public function nullInternal( array $params ) {
345 return $this->newStatus();
348 final public function concatenate( array $params ) {
349 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
350 $status = $this->newStatus();
352 // Try to lock the source files for the scope of this function
353 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager
::LOCK_UW
, $status );
354 if ( $status->isOK() ) {
355 // Actually do the file concatenation...
356 $start_time = microtime( true );
357 $status->merge( $this->doConcatenate( $params ) );
358 $sec = microtime( true ) - $start_time;
359 if ( !$status->isOK() ) {
360 $this->logger
->error( static::class . "-{$this->name}" .
361 " failed to concatenate " . count( $params['srcs'] ) . " file(s) [$sec sec]" );
369 * @see FileBackendStore::concatenate()
370 * @param array $params
371 * @return StatusValue
373 protected function doConcatenate( array $params ) {
374 $status = $this->newStatus();
375 $tmpPath = $params['dst']; // convenience
376 unset( $params['latest'] ); // sanity
378 // Check that the specified temp file is valid...
379 Wikimedia\
suppressWarnings();
380 $ok = ( is_file( $tmpPath ) && filesize( $tmpPath ) == 0 );
381 Wikimedia\restoreWarnings
();
382 if ( !$ok ) { // not present or not empty
383 $status->fatal( 'backend-fail-opentemp', $tmpPath );
388 // Get local FS versions of the chunks needed for the concatenation...
389 $fsFiles = $this->getLocalReferenceMulti( $params );
390 foreach ( $fsFiles as $path => &$fsFile ) {
391 if ( !$fsFile ) { // chunk failed to download?
392 $fsFile = $this->getLocalReference( [ 'src' => $path ] );
393 if ( !$fsFile ) { // retry failed?
394 $status->fatal( 'backend-fail-read', $path );
400 unset( $fsFile ); // unset reference so we can reuse $fsFile
402 // Get a handle for the destination temp file
403 $tmpHandle = fopen( $tmpPath, 'ab' );
404 if ( $tmpHandle === false ) {
405 $status->fatal( 'backend-fail-opentemp', $tmpPath );
410 // Build up the temp file using the source chunks (in order)...
411 foreach ( $fsFiles as $virtualSource => $fsFile ) {
412 // Get a handle to the local FS version
413 $sourceHandle = fopen( $fsFile->getPath(), 'rb' );
414 if ( $sourceHandle === false ) {
415 fclose( $tmpHandle );
416 $status->fatal( 'backend-fail-read', $virtualSource );
420 // Append chunk to file (pass chunk size to avoid magic quotes)
421 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
422 fclose( $sourceHandle );
423 fclose( $tmpHandle );
424 $status->fatal( 'backend-fail-writetemp', $tmpPath );
428 fclose( $sourceHandle );
430 if ( !fclose( $tmpHandle ) ) {
431 $status->fatal( 'backend-fail-closetemp', $tmpPath );
436 clearstatcache(); // temp file changed
441 final protected function doPrepare( array $params ) {
442 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
443 $status = $this->newStatus();
445 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
446 if ( $dir === null ) {
447 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
449 return $status; // invalid storage path
452 if ( $shard !== null ) { // confined to a single container/shard
453 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
454 } else { // directory is on several shards
455 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
456 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
457 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
458 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
466 * @see FileBackendStore::doPrepare()
467 * @param string $container
469 * @param array $params
470 * @return StatusValue
472 protected function doPrepareInternal( $container, $dir, array $params ) {
473 return $this->newStatus();
476 final protected function doSecure( array $params ) {
477 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
478 $status = $this->newStatus();
480 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
481 if ( $dir === null ) {
482 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
484 return $status; // invalid storage path
487 if ( $shard !== null ) { // confined to a single container/shard
488 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
489 } else { // directory is on several shards
490 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
491 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
492 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
493 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
501 * @see FileBackendStore::doSecure()
502 * @param string $container
504 * @param array $params
505 * @return StatusValue
507 protected function doSecureInternal( $container, $dir, array $params ) {
508 return $this->newStatus();
511 final protected function doPublish( array $params ) {
512 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
513 $status = $this->newStatus();
515 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
516 if ( $dir === null ) {
517 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
519 return $status; // invalid storage path
522 if ( $shard !== null ) { // confined to a single container/shard
523 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
524 } else { // directory is on several shards
525 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
526 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
527 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
528 $status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
536 * @see FileBackendStore::doPublish()
537 * @param string $container
539 * @param array $params
540 * @return StatusValue
542 protected function doPublishInternal( $container, $dir, array $params ) {
543 return $this->newStatus();
546 final protected function doClean( array $params ) {
547 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
548 $status = $this->newStatus();
550 // Recursive: first delete all empty subdirs recursively
551 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
552 $subDirsRel = $this->getTopDirectoryList( [ 'dir' => $params['dir'] ] );
553 if ( $subDirsRel !== null ) { // no errors
554 foreach ( $subDirsRel as $subDirRel ) {
555 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
556 $status->merge( $this->doClean( [ 'dir' => $subDir ] +
$params ) );
558 unset( $subDirsRel ); // free directory for rmdir() on Windows (for FS backends)
562 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
563 if ( $dir === null ) {
564 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
566 return $status; // invalid storage path
569 // Attempt to lock this directory...
570 $filesLockEx = [ $params['dir'] ];
571 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
572 if ( !$status->isOK() ) {
573 return $status; // abort
576 if ( $shard !== null ) { // confined to a single container/shard
577 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
578 $this->deleteContainerCache( $fullCont ); // purge cache
579 } else { // directory is on several shards
580 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
581 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
582 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
583 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
584 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
592 * @see FileBackendStore::doClean()
593 * @param string $container
595 * @param array $params
596 * @return StatusValue
598 protected function doCleanInternal( $container, $dir, array $params ) {
599 return $this->newStatus();
602 final public function fileExists( array $params ) {
603 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
604 $stat = $this->getFileStat( $params );
606 return ( $stat === null ) ?
null : (bool)$stat; // null => failure
609 final public function getFileTimestamp( array $params ) {
610 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
611 $stat = $this->getFileStat( $params );
613 return $stat ?
$stat['mtime'] : false;
616 final public function getFileSize( array $params ) {
617 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
618 $stat = $this->getFileStat( $params );
620 return $stat ?
$stat['size'] : false;
623 final public function getFileStat( array $params ) {
624 $path = self
::normalizeStoragePath( $params['src'] );
625 if ( $path === null ) {
626 return false; // invalid storage path
628 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
630 $latest = !empty( $params['latest'] ); // use latest data?
631 $requireSHA1 = !empty( $params['requireSHA1'] ); // require SHA-1 if file exists?
634 $stat = $this->cheapCache
->getField( $path, 'stat', self
::CACHE_TTL
);
635 // Note that some backends, like SwiftFileBackend, sometimes set file stat process
636 // cache entries from mass object listings that do not include the SHA-1. In that
637 // case, loading the persistent stat cache will likely yield the SHA-1.
640 ( $requireSHA1 && is_array( $stat ) && !isset( $stat['sha1'] ) )
642 $this->primeFileCache( [ $path ] ); // check persistent cache
646 $stat = $this->cheapCache
->getField( $path, 'stat', self
::CACHE_TTL
);
647 if ( $stat !== null ) {
648 // If we want the latest data, check that this cached
649 // value was in fact fetched with the latest available data.
650 if ( is_array( $stat ) ) {
652 ( !$latest ||
$stat['latest'] ) &&
653 ( !$requireSHA1 ||
isset( $stat['sha1'] ) )
657 } elseif ( in_array( $stat, [ 'NOT_EXIST', 'NOT_EXIST_LATEST' ] ) ) {
658 if ( !$latest ||
$stat === 'NOT_EXIST_LATEST' ) {
664 $stat = $this->doGetFileStat( $params );
666 if ( is_array( $stat ) ) { // file exists
667 // Strongly consistent backends can automatically set "latest"
668 $stat['latest'] = $stat['latest'] ??
$latest;
669 $this->cheapCache
->setField( $path, 'stat', $stat );
670 $this->setFileCache( $path, $stat ); // update persistent cache
671 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
672 $this->cheapCache
->setField( $path, 'sha1',
673 [ 'hash' => $stat['sha1'], 'latest' => $latest ] );
675 if ( isset( $stat['xattr'] ) ) { // some backends store headers/metadata
676 $stat['xattr'] = self
::normalizeXAttributes( $stat['xattr'] );
677 $this->cheapCache
->setField( $path, 'xattr',
678 [ 'map' => $stat['xattr'], 'latest' => $latest ] );
680 } elseif ( $stat === false ) { // file does not exist
681 $this->cheapCache
->setField( $path, 'stat', $latest ?
'NOT_EXIST_LATEST' : 'NOT_EXIST' );
682 $this->cheapCache
->setField( $path, 'xattr', [ 'map' => false, 'latest' => $latest ] );
683 $this->cheapCache
->setField( $path, 'sha1', [ 'hash' => false, 'latest' => $latest ] );
684 $this->logger
->debug( __METHOD__
. ': File {path} does not exist', [
687 } else { // an error occurred
688 $this->logger
->warning( __METHOD__
. ': Could not stat file {path}', [
697 * @see FileBackendStore::getFileStat()
698 * @param array $params
700 abstract protected function doGetFileStat( array $params );
702 public function getFileContentsMulti( array $params ) {
703 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
705 $params = $this->setConcurrencyFlags( $params );
706 $contents = $this->doGetFileContentsMulti( $params );
712 * @see FileBackendStore::getFileContentsMulti()
713 * @param array $params
716 protected function doGetFileContentsMulti( array $params ) {
718 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
719 Wikimedia\
suppressWarnings();
720 $contents[$path] = $fsFile ?
file_get_contents( $fsFile->getPath() ) : false;
721 Wikimedia\restoreWarnings
();
727 final public function getFileXAttributes( array $params ) {
728 $path = self
::normalizeStoragePath( $params['src'] );
729 if ( $path === null ) {
730 return false; // invalid storage path
732 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
733 $latest = !empty( $params['latest'] ); // use latest data?
734 if ( $this->cheapCache
->hasField( $path, 'xattr', self
::CACHE_TTL
) ) {
735 $stat = $this->cheapCache
->getField( $path, 'xattr' );
736 // If we want the latest data, check that this cached
737 // value was in fact fetched with the latest available data.
738 if ( !$latest ||
$stat['latest'] ) {
742 $fields = $this->doGetFileXAttributes( $params );
743 $fields = is_array( $fields ) ? self
::normalizeXAttributes( $fields ) : false;
744 $this->cheapCache
->setField( $path, 'xattr', [ 'map' => $fields, 'latest' => $latest ] );
750 * @see FileBackendStore::getFileXAttributes()
751 * @param array $params
754 protected function doGetFileXAttributes( array $params ) {
755 return [ 'headers' => [], 'metadata' => [] ]; // not supported
758 final public function getFileSha1Base36( array $params ) {
759 $path = self
::normalizeStoragePath( $params['src'] );
760 if ( $path === null ) {
761 return false; // invalid storage path
763 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
764 $latest = !empty( $params['latest'] ); // use latest data?
765 if ( $this->cheapCache
->hasField( $path, 'sha1', self
::CACHE_TTL
) ) {
766 $stat = $this->cheapCache
->getField( $path, 'sha1' );
767 // If we want the latest data, check that this cached
768 // value was in fact fetched with the latest available data.
769 if ( !$latest ||
$stat['latest'] ) {
770 return $stat['hash'];
773 $hash = $this->doGetFileSha1Base36( $params );
774 $this->cheapCache
->setField( $path, 'sha1', [ 'hash' => $hash, 'latest' => $latest ] );
780 * @see FileBackendStore::getFileSha1Base36()
781 * @param array $params
782 * @return bool|string
784 protected function doGetFileSha1Base36( array $params ) {
785 $fsFile = $this->getLocalReference( $params );
789 return $fsFile->getSha1Base36();
793 final public function getFileProps( array $params ) {
794 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
795 $fsFile = $this->getLocalReference( $params );
796 $props = $fsFile ?
$fsFile->getProps() : FSFile
::placeholderProps();
801 final public function getLocalReferenceMulti( array $params ) {
802 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
804 $params = $this->setConcurrencyFlags( $params );
806 $fsFiles = []; // (path => FSFile)
807 $latest = !empty( $params['latest'] ); // use latest data?
808 // Reuse any files already in process cache...
809 foreach ( $params['srcs'] as $src ) {
810 $path = self
::normalizeStoragePath( $src );
811 if ( $path === null ) {
812 $fsFiles[$src] = null; // invalid storage path
813 } elseif ( $this->expensiveCache
->hasField( $path, 'localRef' ) ) {
814 $val = $this->expensiveCache
->getField( $path, 'localRef' );
815 // If we want the latest data, check that this cached
816 // value was in fact fetched with the latest available data.
817 if ( !$latest ||
$val['latest'] ) {
818 $fsFiles[$src] = $val['object'];
822 // Fetch local references of any remaning files...
823 $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
824 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
825 $fsFiles[$path] = $fsFile;
826 if ( $fsFile ) { // update the process cache...
827 $this->expensiveCache
->setField( $path, 'localRef',
828 [ 'object' => $fsFile, 'latest' => $latest ] );
836 * @see FileBackendStore::getLocalReferenceMulti()
837 * @param array $params
840 protected function doGetLocalReferenceMulti( array $params ) {
841 return $this->doGetLocalCopyMulti( $params );
844 final public function getLocalCopyMulti( array $params ) {
845 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
847 $params = $this->setConcurrencyFlags( $params );
848 $tmpFiles = $this->doGetLocalCopyMulti( $params );
854 * @see FileBackendStore::getLocalCopyMulti()
855 * @param array $params
858 abstract protected function doGetLocalCopyMulti( array $params );
861 * @see FileBackend::getFileHttpUrl()
862 * @param array $params
863 * @return string|null
865 public function getFileHttpUrl( array $params ) {
866 return null; // not supported
869 final public function streamFile( array $params ) {
870 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
871 $status = $this->newStatus();
873 // Always set some fields for subclass convenience
874 $params['options'] = $params['options'] ??
[];
875 $params['headers'] = $params['headers'] ??
[];
877 // Don't stream it out as text/html if there was a PHP error
878 if ( ( empty( $params['headless'] ) ||
$params['headers'] ) && headers_sent() ) {
879 print "Headers already sent, terminating.\n";
880 $status->fatal( 'backend-fail-stream', $params['src'] );
884 $status->merge( $this->doStreamFile( $params ) );
890 * @see FileBackendStore::streamFile()
891 * @param array $params
892 * @return StatusValue
894 protected function doStreamFile( array $params ) {
895 $status = $this->newStatus();
898 $flags |
= !empty( $params['headless'] ) ? HTTPFileStreamer
::STREAM_HEADLESS
: 0;
899 $flags |
= !empty( $params['allowOB'] ) ? HTTPFileStreamer
::STREAM_ALLOW_OB
: 0;
901 $fsFile = $this->getLocalReference( $params );
903 $streamer = new HTTPFileStreamer(
906 'obResetFunc' => $this->obResetFunc
,
907 'streamMimeFunc' => $this->streamMimeFunc
910 $res = $streamer->stream( $params['headers'], true, $params['options'], $flags );
913 HTTPFileStreamer
::send404Message( $params['src'], $flags );
917 $status->fatal( 'backend-fail-stream', $params['src'] );
923 final public function directoryExists( array $params ) {
924 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
925 if ( $dir === null ) {
926 return false; // invalid storage path
928 if ( $shard !== null ) { // confined to a single container/shard
929 return $this->doDirectoryExists( $fullCont, $dir, $params );
930 } else { // directory is on several shards
931 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
932 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
933 $res = false; // response
934 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
935 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
939 } elseif ( $exists === null ) { // error?
940 $res = null; // if we don't find anything, it is indeterminate
949 * @see FileBackendStore::directoryExists()
951 * @param string $container Resolved container name
952 * @param string $dir Resolved path relative to container
953 * @param array $params
956 abstract protected function doDirectoryExists( $container, $dir, array $params );
958 final public function getDirectoryList( array $params ) {
959 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
960 if ( $dir === null ) { // invalid storage path
963 if ( $shard !== null ) {
964 // File listing is confined to a single container/shard
965 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
967 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
968 // File listing spans multiple containers/shards
969 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
971 return new FileBackendStoreShardDirIterator( $this,
972 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
977 * Do not call this function from places outside FileBackend
979 * @see FileBackendStore::getDirectoryList()
981 * @param string $container Resolved container name
982 * @param string $dir Resolved path relative to container
983 * @param array $params
984 * @return Traversable|array|null Returns null on failure
986 abstract public function getDirectoryListInternal( $container, $dir, array $params );
988 final public function getFileList( array $params ) {
989 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
990 if ( $dir === null ) { // invalid storage path
993 if ( $shard !== null ) {
994 // File listing is confined to a single container/shard
995 return $this->getFileListInternal( $fullCont, $dir, $params );
997 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
998 // File listing spans multiple containers/shards
999 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
1001 return new FileBackendStoreShardFileIterator( $this,
1002 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
1007 * Do not call this function from places outside FileBackend
1009 * @see FileBackendStore::getFileList()
1011 * @param string $container Resolved container name
1012 * @param string $dir Resolved path relative to container
1013 * @param array $params
1014 * @return Traversable|array|null Returns null on failure
1016 abstract public function getFileListInternal( $container, $dir, array $params );
1019 * Return a list of FileOp objects from a list of operations.
1020 * Do not call this function from places outside FileBackend.
1022 * The result must have the same number of items as the input.
1023 * An exception is thrown if an unsupported operation is requested.
1025 * @param array $ops Same format as doOperations()
1026 * @return FileOp[] List of FileOp objects
1027 * @throws FileBackendError
1029 final public function getOperationsInternal( array $ops ) {
1031 'store' => StoreFileOp
::class,
1032 'copy' => CopyFileOp
::class,
1033 'move' => MoveFileOp
::class,
1034 'delete' => DeleteFileOp
::class,
1035 'create' => CreateFileOp
::class,
1036 'describe' => DescribeFileOp
::class,
1037 'null' => NullFileOp
::class
1040 $performOps = []; // array of FileOp objects
1041 // Build up ordered array of FileOps...
1042 foreach ( $ops as $operation ) {
1043 $opName = $operation['op'];
1044 if ( isset( $supportedOps[$opName] ) ) {
1045 $class = $supportedOps[$opName];
1046 // Get params for this operation
1047 $params = $operation;
1048 // Append the FileOp class
1049 $performOps[] = new $class( $this, $params, $this->logger
);
1051 throw new FileBackendError( "Operation '$opName' is not supported." );
1059 * Get a list of storage paths to lock for a list of operations
1060 * Returns an array with LockManager::LOCK_UW (shared locks) and
1061 * LockManager::LOCK_EX (exclusive locks) keys, each corresponding
1062 * to a list of storage paths to be locked. All returned paths are
1065 * @param array $performOps List of FileOp objects
1066 * @return array (LockManager::LOCK_UW => path list, LockManager::LOCK_EX => path list)
1068 final public function getPathsToLockForOpsInternal( array $performOps ) {
1069 // Build up a list of files to lock...
1070 $paths = [ 'sh' => [], 'ex' => [] ];
1071 foreach ( $performOps as $fileOp ) {
1072 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1073 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1075 // Optimization: if doing an EX lock anyway, don't also set an SH one
1076 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1077 // Get a shared lock on the parent directory of each path changed
1078 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1081 LockManager
::LOCK_UW
=> $paths['sh'],
1082 LockManager
::LOCK_EX
=> $paths['ex']
1086 public function getScopedLocksForOps( array $ops, StatusValue
$status ) {
1087 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1089 return $this->getScopedFileLocks( $paths, 'mixed', $status );
1092 final protected function doOperationsInternal( array $ops, array $opts ) {
1093 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1094 $status = $this->newStatus();
1096 // Fix up custom header name/value pairs...
1097 $ops = array_map( [ $this, 'sanitizeOpHeaders' ], $ops );
1099 // Build up a list of FileOps...
1100 $performOps = $this->getOperationsInternal( $ops );
1102 // Acquire any locks as needed...
1103 if ( empty( $opts['nonLocking'] ) ) {
1104 // Build up a list of files to lock...
1105 $paths = $this->getPathsToLockForOpsInternal( $performOps );
1106 // Try to lock those files for the scope of this function...
1108 $scopeLock = $this->getScopedFileLocks( $paths, 'mixed', $status );
1109 if ( !$status->isOK() ) {
1110 return $status; // abort
1114 // Clear any file cache entries (after locks acquired)
1115 if ( empty( $opts['preserveCache'] ) ) {
1116 $this->clearCache();
1119 // Build the list of paths involved
1121 foreach ( $performOps as $performOp ) {
1122 $paths = array_merge( $paths, $performOp->storagePathsRead() );
1123 $paths = array_merge( $paths, $performOp->storagePathsChanged() );
1126 // Enlarge the cache to fit the stat entries of these files
1127 $this->cheapCache
->setMaxSize( max( 2 * count( $paths ), self
::CACHE_CHEAP_SIZE
) );
1129 // Load from the persistent container caches
1130 $this->primeContainerCache( $paths );
1131 // Get the latest stat info for all the files (having locked them)
1132 $ok = $this->preloadFileStat( [ 'srcs' => $paths, 'latest' => true ] );
1135 // Actually attempt the operation batch...
1136 $opts = $this->setConcurrencyFlags( $opts );
1137 $subStatus = FileOpBatch
::attempt( $performOps, $opts, $this->fileJournal
);
1139 // If we could not even stat some files, then bail out...
1140 $subStatus = $this->newStatus( 'backend-fail-internal', $this->name
);
1141 foreach ( $ops as $i => $op ) { // mark each op as failed
1142 $subStatus->success
[$i] = false;
1143 ++
$subStatus->failCount
;
1145 $this->logger
->error( static::class . "-{$this->name} " .
1146 " stat failure; aborted operations: " . FormatJson
::encode( $ops ) );
1149 // Merge errors into StatusValue fields
1150 $status->merge( $subStatus );
1151 $status->success
= $subStatus->success
; // not done in merge()
1153 // Shrink the stat cache back to normal size
1154 $this->cheapCache
->setMaxSize( self
::CACHE_CHEAP_SIZE
);
1159 final protected function doQuickOperationsInternal( array $ops ) {
1160 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1161 $status = $this->newStatus();
1163 // Fix up custom header name/value pairs...
1164 $ops = array_map( [ $this, 'sanitizeOpHeaders' ], $ops );
1166 // Clear any file cache entries
1167 $this->clearCache();
1169 $supportedOps = [ 'create', 'store', 'copy', 'move', 'delete', 'describe', 'null' ];
1170 // Parallel ops may be disabled in config due to dependencies (e.g. needing popen())
1171 $async = ( $this->parallelize
=== 'implicit' && count( $ops ) > 1 );
1172 $maxConcurrency = $this->concurrency
; // throttle
1173 /** @var StatusValue[] $statuses */
1174 $statuses = []; // array of (index => StatusValue)
1175 $fileOpHandles = []; // list of (index => handle) arrays
1176 $curFileOpHandles = []; // current handle batch
1177 // Perform the sync-only ops and build up op handles for the async ops...
1178 foreach ( $ops as $index => $params ) {
1179 if ( !in_array( $params['op'], $supportedOps ) ) {
1180 throw new FileBackendError( "Operation '{$params['op']}' is not supported." );
1182 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1183 $subStatus = $this->$method( [ 'async' => $async ] +
$params );
1184 if ( $subStatus->value
instanceof FileBackendStoreOpHandle
) { // async
1185 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1186 $fileOpHandles[] = $curFileOpHandles; // push this batch
1187 $curFileOpHandles = [];
1189 $curFileOpHandles[$index] = $subStatus->value
; // keep index
1190 } else { // error or completed
1191 $statuses[$index] = $subStatus; // keep index
1194 if ( count( $curFileOpHandles ) ) {
1195 $fileOpHandles[] = $curFileOpHandles; // last batch
1197 // Do all the async ops that can be done concurrently...
1198 foreach ( $fileOpHandles as $fileHandleBatch ) {
1199 $statuses = $statuses +
$this->executeOpHandlesInternal( $fileHandleBatch );
1201 // Marshall and merge all the responses...
1202 foreach ( $statuses as $index => $subStatus ) {
1203 $status->merge( $subStatus );
1204 if ( $subStatus->isOK() ) {
1205 $status->success
[$index] = true;
1206 ++
$status->successCount
;
1208 $status->success
[$index] = false;
1209 ++
$status->failCount
;
1217 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1218 * The resulting StatusValue object fields will correspond
1219 * to the order in which the handles where given.
1221 * @param FileBackendStoreOpHandle[] $fileOpHandles
1222 * @return StatusValue[] Map of StatusValue objects
1223 * @throws FileBackendError
1225 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1226 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1228 foreach ( $fileOpHandles as $fileOpHandle ) {
1229 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle
) ) {
1230 throw new InvalidArgumentException( "Expected FileBackendStoreOpHandle object." );
1231 } elseif ( $fileOpHandle->backend
->getName() !== $this->getName() ) {
1232 throw new InvalidArgumentException( "Expected handle for this file backend." );
1236 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1237 foreach ( $fileOpHandles as $fileOpHandle ) {
1238 $fileOpHandle->closeResources();
1245 * @see FileBackendStore::executeOpHandlesInternal()
1247 * @param FileBackendStoreOpHandle[] $fileOpHandles
1249 * @throws FileBackendError
1250 * @return StatusValue[] List of corresponding StatusValue objects
1252 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1253 if ( count( $fileOpHandles ) ) {
1254 throw new LogicException( "Backend does not support asynchronous operations." );
1261 * Normalize and filter HTTP headers from a file operation
1263 * This normalizes and strips long HTTP headers from a file operation.
1264 * Most headers are just numbers, but some are allowed to be long.
1265 * This function is useful for cleaning up headers and avoiding backend
1266 * specific errors, especially in the middle of batch file operations.
1268 * @param array $op Same format as doOperation()
1271 protected function sanitizeOpHeaders( array $op ) {
1272 static $longs = [ 'content-disposition' ];
1274 if ( isset( $op['headers'] ) ) { // op sets HTTP headers
1276 foreach ( $op['headers'] as $name => $value ) {
1277 $name = strtolower( $name );
1278 $maxHVLen = in_array( $name, $longs ) ? INF
: 255;
1279 if ( strlen( $name ) > 255 ||
strlen( $value ) > $maxHVLen ) {
1280 trigger_error( "Header '$name: $value' is too long." );
1282 $newHeaders[$name] = strlen( $value ) ?
$value : ''; // null/false => ""
1285 $op['headers'] = $newHeaders;
1291 final public function preloadCache( array $paths ) {
1292 $fullConts = []; // full container names
1293 foreach ( $paths as $path ) {
1294 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1295 $fullConts[] = $fullCont;
1297 // Load from the persistent file and container caches
1298 $this->primeContainerCache( $fullConts );
1299 $this->primeFileCache( $paths );
1302 final public function clearCache( array $paths = null ) {
1303 if ( is_array( $paths ) ) {
1304 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1305 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1307 if ( $paths === null ) {
1308 $this->cheapCache
->clear();
1309 $this->expensiveCache
->clear();
1311 foreach ( $paths as $path ) {
1312 $this->cheapCache
->clear( $path );
1313 $this->expensiveCache
->clear( $path );
1316 $this->doClearCache( $paths );
1320 * Clears any additional stat caches for storage paths
1322 * @see FileBackend::clearCache()
1324 * @param array|null $paths Storage paths (optional)
1326 protected function doClearCache( array $paths = null ) {
1329 final public function preloadFileStat( array $params ) {
1330 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1331 $success = true; // no network errors
1333 $params['concurrency'] = ( $this->parallelize
!== 'off' ) ?
$this->concurrency
: 1;
1334 $stats = $this->doGetFileStatMulti( $params );
1335 if ( $stats === null ) {
1336 return true; // not supported
1339 $latest = !empty( $params['latest'] ); // use latest data?
1340 foreach ( $stats as $path => $stat ) {
1341 $path = FileBackend
::normalizeStoragePath( $path );
1342 if ( $path === null ) {
1343 continue; // this shouldn't happen
1345 if ( is_array( $stat ) ) { // file exists
1346 // Strongly consistent backends can automatically set "latest"
1347 $stat['latest'] = $stat['latest'] ??
$latest;
1348 $this->cheapCache
->setField( $path, 'stat', $stat );
1349 $this->setFileCache( $path, $stat ); // update persistent cache
1350 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
1351 $this->cheapCache
->setField( $path, 'sha1',
1352 [ 'hash' => $stat['sha1'], 'latest' => $latest ] );
1354 if ( isset( $stat['xattr'] ) ) { // some backends store headers/metadata
1355 $stat['xattr'] = self
::normalizeXAttributes( $stat['xattr'] );
1356 $this->cheapCache
->setField( $path, 'xattr',
1357 [ 'map' => $stat['xattr'], 'latest' => $latest ] );
1359 } elseif ( $stat === false ) { // file does not exist
1360 $this->cheapCache
->setField( $path, 'stat',
1361 $latest ?
'NOT_EXIST_LATEST' : 'NOT_EXIST' );
1362 $this->cheapCache
->setField( $path, 'xattr',
1363 [ 'map' => false, 'latest' => $latest ] );
1364 $this->cheapCache
->setField( $path, 'sha1',
1365 [ 'hash' => false, 'latest' => $latest ] );
1366 $this->logger
->debug( __METHOD__
. ': File {path} does not exist', [
1369 } else { // an error occurred
1371 $this->logger
->warning( __METHOD__
. ': Could not stat file {path}', [
1381 * Get file stat information (concurrently if possible) for several files
1383 * @see FileBackend::getFileStat()
1385 * @param array $params Parameters include:
1386 * - srcs : list of source storage paths
1387 * - latest : use the latest available data
1388 * @return array|null Map of storage paths to array|bool|null (returns null if not supported)
1391 protected function doGetFileStatMulti( array $params ) {
1392 return null; // not supported
1396 * Is this a key/value store where directories are just virtual?
1397 * Virtual directories exists in so much as files exists that are
1398 * prefixed with the directory path followed by a forward slash.
1402 abstract protected function directoriesAreVirtual();
1405 * Check if a short container name is valid
1407 * This checks for length and illegal characters.
1408 * This may disallow certain characters that can appear
1409 * in the prefix used to make the full container name.
1411 * @param string $container
1414 final protected static function isValidShortContainerName( $container ) {
1415 // Suffixes like '.xxx' (hex shard chars) or '.seg' (file segments)
1416 // might be used by subclasses. Reserve the dot character for sanity.
1417 // The only way dots end up in containers (e.g. resolveStoragePath)
1418 // is due to the wikiId container prefix or the above suffixes.
1419 return self
::isValidContainerName( $container ) && !preg_match( '/[.]/', $container );
1423 * Check if a full container name is valid
1425 * This checks for length and illegal characters.
1426 * Limiting the characters makes migrations to other stores easier.
1428 * @param string $container
1431 final protected static function isValidContainerName( $container ) {
1432 // This accounts for NTFS, Swift, and Ceph restrictions
1433 // and disallows directory separators or traversal characters.
1434 // Note that matching strings URL encode to the same string;
1435 // in Swift/Ceph, the length restriction is *after* URL encoding.
1436 return (bool)preg_match( '/^[a-z0-9][a-z0-9-_.]{0,199}$/i', $container );
1440 * Splits a storage path into an internal container name,
1441 * an internal relative file name, and a container shard suffix.
1442 * Any shard suffix is already appended to the internal container name.
1443 * This also checks that the storage path is valid and within this backend.
1445 * If the container is sharded but a suffix could not be determined,
1446 * this means that the path can only refer to a directory and can only
1447 * be scanned by looking in all the container shards.
1449 * @param string $storagePath
1450 * @return array (container, path, container suffix) or (null, null, null) if invalid
1452 final protected function resolveStoragePath( $storagePath ) {
1453 list( $backend, $shortCont, $relPath ) = self
::splitStoragePath( $storagePath );
1454 if ( $backend === $this->name
) { // must be for this backend
1455 $relPath = self
::normalizeContainerPath( $relPath );
1456 if ( $relPath !== null && self
::isValidShortContainerName( $shortCont ) ) {
1457 // Get shard for the normalized path if this container is sharded
1458 $cShard = $this->getContainerShard( $shortCont, $relPath );
1459 // Validate and sanitize the relative path (backend-specific)
1460 $relPath = $this->resolveContainerPath( $shortCont, $relPath );
1461 if ( $relPath !== null ) {
1462 // Prepend any wiki ID prefix to the container name
1463 $container = $this->fullContainerName( $shortCont );
1464 if ( self
::isValidContainerName( $container ) ) {
1465 // Validate and sanitize the container name (backend-specific)
1466 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1467 if ( $container !== null ) {
1468 return [ $container, $relPath, $cShard ];
1475 return [ null, null, null ];
1479 * Like resolveStoragePath() except null values are returned if
1480 * the container is sharded and the shard could not be determined
1481 * or if the path ends with '/'. The latter case is illegal for FS
1482 * backends and can confuse listings for object store backends.
1484 * This function is used when resolving paths that must be valid
1485 * locations for files. Directory and listing functions should
1486 * generally just use resolveStoragePath() instead.
1488 * @see FileBackendStore::resolveStoragePath()
1490 * @param string $storagePath
1491 * @return array (container, path) or (null, null) if invalid
1493 final protected function resolveStoragePathReal( $storagePath ) {
1494 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1495 if ( $cShard !== null && substr( $relPath, -1 ) !== '/' ) {
1496 return [ $container, $relPath ];
1499 return [ null, null ];
1503 * Get the container name shard suffix for a given path.
1504 * Any empty suffix means the container is not sharded.
1506 * @param string $container Container name
1507 * @param string $relPath Storage path relative to the container
1508 * @return string|null Returns null if shard could not be determined
1510 final protected function getContainerShard( $container, $relPath ) {
1511 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1512 if ( $levels == 1 ||
$levels == 2 ) {
1513 // Hash characters are either base 16 or 36
1514 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1515 // Get a regex that represents the shard portion of paths.
1516 // The concatenation of the captures gives us the shard.
1517 if ( $levels === 1 ) { // 16 or 36 shards per container
1518 $hashDirRegex = '(' . $char . ')';
1519 } else { // 256 or 1296 shards per container
1520 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1521 $hashDirRegex = $char . '/(' . $char . '{2})';
1522 } else { // short hash dir format (e.g. "a/b/c")
1523 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1526 // Allow certain directories to be above the hash dirs so as
1527 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1528 // They must be 2+ chars to avoid any hash directory ambiguity.
1530 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1531 return '.' . implode( '', array_slice( $m, 1 ) );
1534 return null; // failed to match
1537 return ''; // no sharding
1541 * Check if a storage path maps to a single shard.
1542 * Container dirs like "a", where the container shards on "x/xy",
1543 * can reside on several shards. Such paths are tricky to handle.
1545 * @param string $storagePath Storage path
1548 final public function isSingleShardPathInternal( $storagePath ) {
1549 list( , , $shard ) = $this->resolveStoragePath( $storagePath );
1551 return ( $shard !== null );
1555 * Get the sharding config for a container.
1556 * If greater than 0, then all file storage paths within
1557 * the container are required to be hashed accordingly.
1559 * @param string $container
1560 * @return array (integer levels, integer base, repeat flag) or (0, 0, false)
1562 final protected function getContainerHashLevels( $container ) {
1563 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1564 $config = $this->shardViaHashLevels
[$container];
1565 $hashLevels = (int)$config['levels'];
1566 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1567 $hashBase = (int)$config['base'];
1568 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1569 return [ $hashLevels, $hashBase, $config['repeat'] ];
1574 return [ 0, 0, false ]; // no sharding
1578 * Get a list of full container shard suffixes for a container
1580 * @param string $container
1583 final protected function getContainerSuffixes( $container ) {
1585 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1586 if ( $digits > 0 ) {
1587 $numShards = $base ** $digits;
1588 for ( $index = 0; $index < $numShards; $index++
) {
1589 $shards[] = '.' . Wikimedia\base_convert
( $index, 10, $base, $digits );
1597 * Get the full container name, including the wiki ID prefix
1599 * @param string $container
1602 final protected function fullContainerName( $container ) {
1603 if ( $this->domainId
!= '' ) {
1604 return "{$this->domainId}-$container";
1611 * Resolve a container name, checking if it's allowed by the backend.
1612 * This is intended for internal use, such as encoding illegal chars.
1613 * Subclasses can override this to be more restrictive.
1615 * @param string $container
1616 * @return string|null
1618 protected function resolveContainerName( $container ) {
1623 * Resolve a relative storage path, checking if it's allowed by the backend.
1624 * This is intended for internal use, such as encoding illegal chars or perhaps
1625 * getting absolute paths (e.g. FS based backends). Note that the relative path
1626 * may be the empty string (e.g. the path is simply to the container).
1628 * @param string $container Container name
1629 * @param string $relStoragePath Storage path relative to the container
1630 * @return string|null Path or null if not valid
1632 protected function resolveContainerPath( $container, $relStoragePath ) {
1633 return $relStoragePath;
1637 * Get the cache key for a container
1639 * @param string $container Resolved container name
1642 private function containerCacheKey( $container ) {
1643 return "filebackend:{$this->name}:{$this->domainId}:container:{$container}";
1647 * Set the cached info for a container
1649 * @param string $container Resolved container name
1650 * @param array $val Information to cache
1652 final protected function setContainerCache( $container, array $val ) {
1653 $this->memCache
->set( $this->containerCacheKey( $container ), $val, 14 * 86400 );
1657 * Delete the cached info for a container.
1658 * The cache key is salted for a while to prevent race conditions.
1660 * @param string $container Resolved container name
1662 final protected function deleteContainerCache( $container ) {
1663 if ( !$this->memCache
->delete( $this->containerCacheKey( $container ), 300 ) ) {
1664 trigger_error( "Unable to delete stat cache for container $container." );
1669 * Do a batch lookup from cache for container stats for all containers
1670 * used in a list of container names or storage paths objects.
1671 * This loads the persistent cache values into the process cache.
1673 * @param array $items
1675 final protected function primeContainerCache( array $items ) {
1676 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1678 $paths = []; // list of storage paths
1679 $contNames = []; // (cache key => resolved container name)
1680 // Get all the paths/containers from the items...
1681 foreach ( $items as $item ) {
1682 if ( self
::isStoragePath( $item ) ) {
1684 } elseif ( is_string( $item ) ) { // full container name
1685 $contNames[$this->containerCacheKey( $item )] = $item;
1688 // Get all the corresponding cache keys for paths...
1689 foreach ( $paths as $path ) {
1690 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1691 if ( $fullCont !== null ) { // valid path for this backend
1692 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1696 $contInfo = []; // (resolved container name => cache value)
1697 // Get all cache entries for these container cache keys...
1698 $values = $this->memCache
->getMulti( array_keys( $contNames ) );
1699 foreach ( $values as $cacheKey => $val ) {
1700 $contInfo[$contNames[$cacheKey]] = $val;
1703 // Populate the container process cache for the backend...
1704 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1708 * Fill the backend-specific process cache given an array of
1709 * resolved container names and their corresponding cached info.
1710 * Only containers that actually exist should appear in the map.
1712 * @param array $containerInfo Map of resolved container names to cached info
1714 protected function doPrimeContainerCache( array $containerInfo ) {
1718 * Get the cache key for a file path
1720 * @param string $path Normalized storage path
1723 private function fileCacheKey( $path ) {
1724 return "filebackend:{$this->name}:{$this->domainId}:file:" . sha1( $path );
1728 * Set the cached stat info for a file path.
1729 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1730 * salting for the case when a file is created at a path were there was none before.
1732 * @param string $path Storage path
1733 * @param array $val Stat information to cache
1735 final protected function setFileCache( $path, array $val ) {
1736 $path = FileBackend
::normalizeStoragePath( $path );
1737 if ( $path === null ) {
1738 return; // invalid storage path
1740 $mtime = ConvertibleTimestamp
::convert( TS_UNIX
, $val['mtime'] );
1741 $ttl = $this->memCache
->adaptiveTTL( $mtime, 7 * 86400, 300, 0.1 );
1742 $key = $this->fileCacheKey( $path );
1743 // Set the cache unless it is currently salted.
1744 $this->memCache
->set( $key, $val, $ttl );
1748 * Delete the cached stat info for a file path.
1749 * The cache key is salted for a while to prevent race conditions.
1750 * Since negatives (404s) are not cached, this does not need to be called when
1751 * a file is created at a path were there was none before.
1753 * @param string $path Storage path
1755 final protected function deleteFileCache( $path ) {
1756 $path = FileBackend
::normalizeStoragePath( $path );
1757 if ( $path === null ) {
1758 return; // invalid storage path
1760 if ( !$this->memCache
->delete( $this->fileCacheKey( $path ), 300 ) ) {
1761 trigger_error( "Unable to delete stat cache for file $path." );
1766 * Do a batch lookup from cache for file stats for all paths
1767 * used in a list of storage paths or FileOp objects.
1768 * This loads the persistent cache values into the process cache.
1770 * @param array $items List of storage paths
1772 final protected function primeFileCache( array $items ) {
1773 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1775 $paths = []; // list of storage paths
1776 $pathNames = []; // (cache key => storage path)
1777 // Get all the paths/containers from the items...
1778 foreach ( $items as $item ) {
1779 if ( self
::isStoragePath( $item ) ) {
1780 $paths[] = FileBackend
::normalizeStoragePath( $item );
1783 // Get rid of any paths that failed normalization...
1784 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1785 // Get all the corresponding cache keys for paths...
1786 foreach ( $paths as $path ) {
1787 list( , $rel, ) = $this->resolveStoragePath( $path );
1788 if ( $rel !== null ) { // valid path for this backend
1789 $pathNames[$this->fileCacheKey( $path )] = $path;
1792 // Get all cache entries for these file cache keys...
1793 $values = $this->memCache
->getMulti( array_keys( $pathNames ) );
1794 foreach ( $values as $cacheKey => $val ) {
1795 $path = $pathNames[$cacheKey];
1796 if ( is_array( $val ) ) {
1797 $val['latest'] = false; // never completely trust cache
1798 $this->cheapCache
->setField( $path, 'stat', $val );
1799 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1800 $this->cheapCache
->setField( $path, 'sha1',
1801 [ 'hash' => $val['sha1'], 'latest' => false ] );
1803 if ( isset( $val['xattr'] ) ) { // some backends store headers/metadata
1804 $val['xattr'] = self
::normalizeXAttributes( $val['xattr'] );
1805 $this->cheapCache
->setField( $path, 'xattr',
1806 [ 'map' => $val['xattr'], 'latest' => false ] );
1813 * Normalize file headers/metadata to the FileBackend::getFileXAttributes() format
1815 * @param array $xattr
1819 final protected static function normalizeXAttributes( array $xattr ) {
1820 $newXAttr = [ 'headers' => [], 'metadata' => [] ];
1822 foreach ( $xattr['headers'] as $name => $value ) {
1823 $newXAttr['headers'][strtolower( $name )] = $value;
1826 foreach ( $xattr['metadata'] as $name => $value ) {
1827 $newXAttr['metadata'][strtolower( $name )] = $value;
1834 * Set the 'concurrency' option from a list of operation options
1836 * @param array $opts Map of operation options
1839 final protected function setConcurrencyFlags( array $opts ) {
1840 $opts['concurrency'] = 1; // off
1841 if ( $this->parallelize
=== 'implicit' ) {
1842 if ( !isset( $opts['parallelize'] ) ||
$opts['parallelize'] ) {
1843 $opts['concurrency'] = $this->concurrency
;
1845 } elseif ( $this->parallelize
=== 'explicit' ) {
1846 if ( !empty( $opts['parallelize'] ) ) {
1847 $opts['concurrency'] = $this->concurrency
;
1855 * Get the content type to use in HEAD/GET requests for a file
1857 * @param string $storagePath
1858 * @param string|null $content File data
1859 * @param string|null $fsPath File system path
1860 * @return string MIME type
1862 protected function getContentType( $storagePath, $content, $fsPath ) {
1863 if ( $this->mimeCallback
) {
1864 return call_user_func_array( $this->mimeCallback
, func_get_args() );
1867 $mime = ( $fsPath !== null ) ?
mime_content_type( $fsPath ) : false;
1868 return $mime ?
: 'unknown/unknown';
1873 * FileBackendStore helper class for performing asynchronous file operations.
1875 * For example, calling FileBackendStore::createInternal() with the "async"
1876 * param flag may result in a StatusValue that contains this object as a value.
1877 * This class is largely backend-specific and is mostly just "magic" to be
1878 * passed to FileBackendStore::executeOpHandlesInternal().
1880 abstract class FileBackendStoreOpHandle
{
1882 public $params = []; // params to caller functions
1883 /** @var FileBackendStore */
1886 public $resourcesToClose = [];
1888 public $call; // string; name that identifies the function called
1891 * Close all open file handles
1893 public function closeResources() {
1894 array_map( 'fclose', $this->resourcesToClose
);
1899 * FileBackendStore helper function to handle listings that span container shards.
1900 * Do not use this class from places outside of FileBackendStore.
1902 * @ingroup FileBackend
1904 abstract class FileBackendStoreShardListIterator
extends FilterIterator
{
1905 /** @var FileBackendStore */
1911 /** @var string Full container name */
1912 protected $container;
1914 /** @var string Resolved relative path */
1915 protected $directory;
1918 protected $multiShardPaths = []; // (rel path => 1)
1921 * @param FileBackendStore $backend
1922 * @param string $container Full storage container name
1923 * @param string $dir Storage directory relative to container
1924 * @param array $suffixes List of container shard suffixes
1925 * @param array $params
1927 public function __construct(
1928 FileBackendStore
$backend, $container, $dir, array $suffixes, array $params
1930 $this->backend
= $backend;
1931 $this->container
= $container;
1932 $this->directory
= $dir;
1933 $this->params
= $params;
1935 $iter = new AppendIterator();
1936 foreach ( $suffixes as $suffix ) {
1937 $iter->append( $this->listFromShard( $this->container
. $suffix ) );
1940 parent
::__construct( $iter );
1943 public function accept() {
1944 $rel = $this->getInnerIterator()->current(); // path relative to given directory
1945 $path = $this->params
['dir'] . "/{$rel}"; // full storage path
1946 if ( $this->backend
->isSingleShardPathInternal( $path ) ) {
1947 return true; // path is only on one shard; no issue with duplicates
1948 } elseif ( isset( $this->multiShardPaths
[$rel] ) ) {
1949 // Don't keep listing paths that are on multiple shards
1952 $this->multiShardPaths
[$rel] = 1;
1958 public function rewind() {
1960 $this->multiShardPaths
= [];
1964 * Get the list for a given container shard
1966 * @param string $container Resolved container name
1969 abstract protected function listFromShard( $container );
1973 * Iterator for listing directories
1975 class FileBackendStoreShardDirIterator
extends FileBackendStoreShardListIterator
{
1976 protected function listFromShard( $container ) {
1977 $list = $this->backend
->getDirectoryListInternal(
1978 $container, $this->directory
, $this->params
);
1979 if ( $list === null ) {
1980 return new ArrayIterator( [] );
1982 return is_array( $list ) ?
new ArrayIterator( $list ) : $list;
1988 * Iterator for listing regular files
1990 class FileBackendStoreShardFileIterator
extends FileBackendStoreShardListIterator
{
1991 protected function listFromShard( $container ) {
1992 $list = $this->backend
->getFileListInternal(
1993 $container, $this->directory
, $this->params
);
1994 if ( $list === null ) {
1995 return new ArrayIterator( [] );
1997 return is_array( $list ) ?
new ArrayIterator( $list ) : $list;