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
24 namespace Wikimedia\FileBackend
;
26 use InvalidArgumentException
;
29 use MediaWiki\Json\FormatJson
;
30 use Shellbox\Command\BoxedCommand
;
33 use Wikimedia\AtEase\AtEase
;
34 use Wikimedia\FileBackend\FileIteration\FileBackendStoreShardDirIterator
;
35 use Wikimedia\FileBackend\FileIteration\FileBackendStoreShardFileIterator
;
36 use Wikimedia\FileBackend\FileOpHandle\FileBackendStoreOpHandle
;
37 use Wikimedia\FileBackend\FileOps\CopyFileOp
;
38 use Wikimedia\FileBackend\FileOps\CreateFileOp
;
39 use Wikimedia\FileBackend\FileOps\DeleteFileOp
;
40 use Wikimedia\FileBackend\FileOps\DescribeFileOp
;
41 use Wikimedia\FileBackend\FileOps\FileOp
;
42 use Wikimedia\FileBackend\FileOps\MoveFileOp
;
43 use Wikimedia\FileBackend\FileOps\NullFileOp
;
44 use Wikimedia\FileBackend\FileOps\StoreFileOp
;
45 use Wikimedia\FileBackend\FSFile\FSFile
;
46 use Wikimedia\ObjectCache\BagOStuff
;
47 use Wikimedia\ObjectCache\EmptyBagOStuff
;
48 use Wikimedia\ObjectCache\WANObjectCache
;
49 use Wikimedia\Timestamp\ConvertibleTimestamp
;
52 * @brief Base class for all backends using particular storage medium.
54 * This class defines the methods as abstract that subclasses must implement.
55 * Outside callers should *not* use functions with "Internal" in the name.
57 * The FileBackend operations are implemented using basic functions
58 * such as storeInternal(), copyInternal(), deleteInternal() and the like.
59 * This class is also responsible for path resolution and sanitization.
62 * @ingroup FileBackend
65 abstract class FileBackendStore
extends FileBackend
{
66 /** @var WANObjectCache */
70 /** @var MapCacheLRU Map of paths to small (RAM/disk) cache items */
71 protected $cheapCache;
72 /** @var MapCacheLRU Map of paths to large (RAM/disk) cache items */
73 protected $expensiveCache;
75 /** @var array<string,array> Map of container names to sharding config */
76 protected $shardViaHashLevels = [];
78 /** @var callable|null Method to get the MIME type of files */
79 protected $mimeCallback;
81 /** @var int Size in bytes, defaults to 32 GiB */
82 protected $maxFileSize = 32 * 1024 * 1024 * 1024;
84 protected const CACHE_TTL
= 10; // integer; TTL in seconds for process cache entries
85 protected const CACHE_CHEAP_SIZE
= 500; // integer; max entries in "cheap cache"
86 protected const CACHE_EXPENSIVE_SIZE
= 5; // integer; max entries in "expensive cache"
88 /** @var false Idiom for "no result due to missing file" (since 1.34) */
89 protected const RES_ABSENT
= false;
90 /** @var null Idiom for "no result due to I/O errors" (since 1.34) */
91 protected const RES_ERROR
= null;
93 /** @var string File does not exist according to a normal stat query */
94 protected const ABSENT_NORMAL
= 'FNE-N';
95 /** @var string File does not exist according to a "latest"-mode stat query */
96 protected const ABSENT_LATEST
= 'FNE-L';
99 * @see FileBackend::__construct()
100 * Additional $config params include:
101 * - srvCache : BagOStuff cache to APC or the like.
102 * - wanCache : WANObjectCache object to use for persistent caching.
103 * - mimeCallback : Callback that takes (storage path, content, file system path) and
104 * returns the MIME type of the file or 'unknown/unknown'. The file
105 * system path parameter should be used if the content one is null.
109 * @param array $config
111 public function __construct( array $config ) {
112 parent
::__construct( $config );
113 $this->mimeCallback
= $config['mimeCallback'] ??
null;
114 $this->srvCache
= new EmptyBagOStuff(); // disabled by default
115 $this->memCache
= WANObjectCache
::newEmpty(); // disabled by default
116 $this->cheapCache
= new MapCacheLRU( self
::CACHE_CHEAP_SIZE
);
117 $this->expensiveCache
= new MapCacheLRU( self
::CACHE_EXPENSIVE_SIZE
);
121 * Get the maximum allowable file size given backend
122 * medium restrictions and basic performance constraints.
123 * Do not call this function from places outside FileBackend and FileOp.
127 final public function maxFileSizeInternal() {
128 return min( $this->maxFileSize
, PHP_INT_MAX
);
132 * Check if a file can be created or changed at a given storage path in the backend
134 * FS backends should check that the parent directory exists, files can be written
135 * under it, and that any file already there is both readable and writable.
136 * Backends using key/value stores should check if the container exists.
138 * @param string $storagePath
141 abstract public function isPathUsableInternal( $storagePath );
144 * Create a file in the backend with the given contents.
145 * This will overwrite any file that exists at the destination.
146 * Do not call this function from places outside FileBackend and FileOp.
149 * - content : the raw file contents
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 createInternal( array $params ) {
162 /** @noinspection PhpUnusedLocalVariableInspection */
163 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
165 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
166 $status = $this->newStatus( 'backend-fail-maxsize',
167 $params['dst'], $this->maxFileSizeInternal() );
169 $status = $this->doCreateInternal( $params );
170 $this->clearCache( [ $params['dst'] ] );
171 if ( $params['dstExists'] ??
true ) {
172 $this->deleteFileCache( $params['dst'] ); // persistent cache
180 * @see FileBackendStore::createInternal()
181 * @param array $params
182 * @return StatusValue
184 abstract protected function doCreateInternal( array $params );
187 * Store a file into the backend from a file on disk.
188 * This will overwrite any file that exists at the destination.
189 * Do not call this function from places outside FileBackend and FileOp.
192 * - src : source path on disk
193 * - dst : destination storage path
194 * - headers : HTTP header name/value map
195 * - async : StatusValue will be returned immediately if supported.
196 * If the StatusValue is OK, then its value field will be
197 * set to a FileBackendStoreOpHandle object.
198 * - dstExists : Whether a file exists at the destination (optimization).
199 * Callers can use "false" if no existing file is being changed.
201 * @param array $params
202 * @return StatusValue
204 final public function storeInternal( array $params ) {
205 /** @noinspection PhpUnusedLocalVariableInspection */
206 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
208 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
209 $status = $this->newStatus( 'backend-fail-maxsize',
210 $params['dst'], $this->maxFileSizeInternal() );
212 $status = $this->doStoreInternal( $params );
213 $this->clearCache( [ $params['dst'] ] );
214 if ( $params['dstExists'] ??
true ) {
215 $this->deleteFileCache( $params['dst'] ); // persistent cache
223 * @see FileBackendStore::storeInternal()
224 * @param array $params
225 * @return StatusValue
227 abstract protected function doStoreInternal( array $params );
230 * Copy a file from one storage path to another in the backend.
231 * This will overwrite any file that exists at the destination.
232 * Do not call this function from places outside FileBackend and FileOp.
235 * - src : source storage path
236 * - dst : destination storage path
237 * - ignoreMissingSource : do nothing if the source file does not exist
238 * - headers : HTTP header name/value map
239 * - async : StatusValue will be returned immediately if supported.
240 * If the StatusValue is OK, then its value field will be
241 * set to a FileBackendStoreOpHandle object.
242 * - dstExists : Whether a file exists at the destination (optimization).
243 * Callers can use "false" if no existing file is being changed.
245 * @param array $params
246 * @return StatusValue
248 final public function copyInternal( array $params ) {
249 /** @noinspection PhpUnusedLocalVariableInspection */
250 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
252 $status = $this->doCopyInternal( $params );
253 $this->clearCache( [ $params['dst'] ] );
254 if ( $params['dstExists'] ??
true ) {
255 $this->deleteFileCache( $params['dst'] ); // persistent cache
262 * @see FileBackendStore::copyInternal()
263 * @param array $params
264 * @return StatusValue
266 abstract protected function doCopyInternal( array $params );
269 * Delete a file at the storage path.
270 * Do not call this function from places outside FileBackend and FileOp.
273 * - src : source storage path
274 * - ignoreMissingSource : do nothing if the source file does not exist
275 * - async : StatusValue will be returned immediately if supported.
276 * If the StatusValue is OK, then its value field will be
277 * set to a FileBackendStoreOpHandle object.
279 * @param array $params
280 * @return StatusValue
282 final public function deleteInternal( array $params ) {
283 /** @noinspection PhpUnusedLocalVariableInspection */
284 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
286 $status = $this->doDeleteInternal( $params );
287 $this->clearCache( [ $params['src'] ] );
288 $this->deleteFileCache( $params['src'] ); // persistent cache
293 * @see FileBackendStore::deleteInternal()
294 * @param array $params
295 * @return StatusValue
297 abstract protected function doDeleteInternal( array $params );
300 * Move a file from one storage path to another in the backend.
301 * This will overwrite any file that exists at the destination.
302 * Do not call this function from places outside FileBackend and FileOp.
305 * - src : source storage path
306 * - dst : destination storage path
307 * - ignoreMissingSource : do nothing if the source file does not exist
308 * - headers : HTTP header name/value map
309 * - async : StatusValue will be returned immediately if supported.
310 * If the StatusValue is OK, then its value field will be
311 * set to a FileBackendStoreOpHandle object.
312 * - dstExists : Whether a file exists at the destination (optimization).
313 * Callers can use "false" if no existing file is being changed.
315 * @param array $params
316 * @return StatusValue
318 final public function moveInternal( array $params ) {
319 /** @noinspection PhpUnusedLocalVariableInspection */
320 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
322 $status = $this->doMoveInternal( $params );
323 $this->clearCache( [ $params['src'], $params['dst'] ] );
324 $this->deleteFileCache( $params['src'] ); // persistent cache
325 if ( $params['dstExists'] ??
true ) {
326 $this->deleteFileCache( $params['dst'] ); // persistent cache
333 * @see FileBackendStore::moveInternal()
334 * @param array $params
335 * @return StatusValue
337 abstract protected function doMoveInternal( array $params );
340 * Alter metadata for a file at the storage path.
341 * Do not call this function from places outside FileBackend and FileOp.
344 * - src : source storage path
345 * - headers : HTTP header name/value map
346 * - async : StatusValue will be returned immediately if supported.
347 * If the StatusValue is OK, then its value field will be
348 * set to a FileBackendStoreOpHandle object.
350 * @param array $params
351 * @return StatusValue
353 final public function describeInternal( array $params ) {
354 /** @noinspection PhpUnusedLocalVariableInspection */
355 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
357 if ( count( $params['headers'] ) ) {
358 $status = $this->doDescribeInternal( $params );
359 $this->clearCache( [ $params['src'] ] );
360 $this->deleteFileCache( $params['src'] ); // persistent cache
362 $status = $this->newStatus(); // nothing to do
369 * @see FileBackendStore::describeInternal()
370 * @stable to override
371 * @param array $params
372 * @return StatusValue
374 protected function doDescribeInternal( array $params ) {
375 return $this->newStatus();
379 * No-op file operation that does nothing.
380 * Do not call this function from places outside FileBackend and FileOp.
382 * @param array $params
383 * @return StatusValue
385 final public function nullInternal( array $params ) {
386 return $this->newStatus();
389 final public function concatenate( array $params ) {
390 /** @noinspection PhpUnusedLocalVariableInspection */
391 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
392 $status = $this->newStatus();
394 // Try to lock the source files for the scope of this function
395 /** @noinspection PhpUnusedLocalVariableInspection */
396 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager
::LOCK_UW
, $status );
397 if ( $status->isOK() ) {
398 // Actually do the file concatenation...
399 $start_time = microtime( true );
400 $status->merge( $this->doConcatenate( $params ) );
401 $sec = microtime( true ) - $start_time;
402 if ( !$status->isOK() ) {
403 $this->logger
->error( static::class . "-{$this->name}" .
404 " failed to concatenate " . count( $params['srcs'] ) . " file(s) [$sec sec]" );
412 * @see FileBackendStore::concatenate()
413 * @stable to override
414 * @param array $params
415 * @return StatusValue
417 protected function doConcatenate( array $params ) {
418 $status = $this->newStatus();
419 $tmpPath = $params['dst'];
420 unset( $params['latest'] );
422 // Check that the specified temp file is valid...
423 AtEase
::suppressWarnings();
424 $ok = ( is_file( $tmpPath ) && filesize( $tmpPath ) == 0 );
425 AtEase
::restoreWarnings();
426 if ( !$ok ) { // not present or not empty
427 $status->fatal( 'backend-fail-opentemp', $tmpPath );
432 // Get local FS versions of the chunks needed for the concatenation...
433 $fsFiles = $this->getLocalReferenceMulti( $params );
434 foreach ( $fsFiles as $path => &$fsFile ) {
435 if ( !$fsFile ) { // chunk failed to download?
436 $fsFile = $this->getLocalReference( [ 'src' => $path ] );
437 if ( !$fsFile ) { // retry failed?
439 $fsFile === self
::RES_ERROR ?
'backend-fail-read' : 'backend-fail-notexists',
447 unset( $fsFile ); // unset reference so we can reuse $fsFile
449 // Get a handle for the destination temp file
450 $tmpHandle = fopen( $tmpPath, 'ab' );
451 if ( $tmpHandle === false ) {
452 $status->fatal( 'backend-fail-opentemp', $tmpPath );
457 // Build up the temp file using the source chunks (in order)...
458 foreach ( $fsFiles as $virtualSource => $fsFile ) {
459 // Get a handle to the local FS version
460 $sourceHandle = fopen( $fsFile->getPath(), 'rb' );
461 if ( $sourceHandle === false ) {
462 fclose( $tmpHandle );
463 $status->fatal( 'backend-fail-read', $virtualSource );
467 // Append chunk to file (pass chunk size to avoid magic quotes)
468 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
469 fclose( $sourceHandle );
470 fclose( $tmpHandle );
471 $status->fatal( 'backend-fail-writetemp', $tmpPath );
475 fclose( $sourceHandle );
477 if ( !fclose( $tmpHandle ) ) {
478 $status->fatal( 'backend-fail-closetemp', $tmpPath );
483 clearstatcache(); // temp file changed
491 final protected function doPrepare( array $params ) {
492 /** @noinspection PhpUnusedLocalVariableInspection */
493 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
494 $status = $this->newStatus();
496 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
497 if ( $dir === null ) {
498 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
500 return $status; // invalid storage path
503 if ( $shard !== null ) { // confined to a single container/shard
504 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
505 } else { // directory is on several shards
506 $this->logger
->debug( __METHOD__
. ": iterating over all container shards." );
507 [ , $shortCont, ] = self
::splitStoragePath( $params['dir'] );
508 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
509 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
517 * @see FileBackendStore::doPrepare()
518 * @stable to override
519 * @param string $container
521 * @param array $params
522 * @return StatusValue Good status without value for success, fatal otherwise.
524 protected function doPrepareInternal( $container, $dir, array $params ) {
525 return $this->newStatus();
528 final protected function doSecure( array $params ) {
529 /** @noinspection PhpUnusedLocalVariableInspection */
530 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
531 $status = $this->newStatus();
533 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
534 if ( $dir === null ) {
535 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
537 return $status; // invalid storage path
540 if ( $shard !== null ) { // confined to a single container/shard
541 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
542 } else { // directory is on several shards
543 $this->logger
->debug( __METHOD__
. ": iterating over all container shards." );
544 [ , $shortCont, ] = self
::splitStoragePath( $params['dir'] );
545 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
546 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
554 * @see FileBackendStore::doSecure()
555 * @stable to override
556 * @param string $container
558 * @param array $params
559 * @return StatusValue Good status without value for success, fatal otherwise.
561 protected function doSecureInternal( $container, $dir, array $params ) {
562 return $this->newStatus();
565 final protected function doPublish( array $params ) {
566 /** @noinspection PhpUnusedLocalVariableInspection */
567 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
568 $status = $this->newStatus();
570 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
571 if ( $dir === null ) {
572 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
574 return $status; // invalid storage path
577 if ( $shard !== null ) { // confined to a single container/shard
578 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
579 } else { // directory is on several shards
580 $this->logger
->debug( __METHOD__
. ": iterating over all container shards." );
581 [ , $shortCont, ] = self
::splitStoragePath( $params['dir'] );
582 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
583 $status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
591 * @see FileBackendStore::doPublish()
592 * @stable to override
593 * @param string $container
595 * @param array $params
596 * @return StatusValue
598 protected function doPublishInternal( $container, $dir, array $params ) {
599 return $this->newStatus();
602 final protected function doClean( array $params ) {
603 /** @noinspection PhpUnusedLocalVariableInspection */
604 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
605 $status = $this->newStatus();
607 // Recursive: first delete all empty subdirs recursively
608 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
609 $subDirsRel = $this->getTopDirectoryList( [ 'dir' => $params['dir'] ] );
610 if ( $subDirsRel !== null ) { // no errors
611 foreach ( $subDirsRel as $subDirRel ) {
612 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
613 $status->merge( $this->doClean( [ 'dir' => $subDir ] +
$params ) );
615 unset( $subDirsRel ); // free directory for rmdir() on Windows (for FS backends)
619 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
620 if ( $dir === null ) {
621 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
623 return $status; // invalid storage path
626 // Attempt to lock this directory...
627 $filesLockEx = [ $params['dir'] ];
628 /** @noinspection PhpUnusedLocalVariableInspection */
629 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
630 if ( !$status->isOK() ) {
631 return $status; // abort
634 if ( $shard !== null ) { // confined to a single container/shard
635 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
636 $this->deleteContainerCache( $fullCont ); // purge cache
637 } else { // directory is on several shards
638 $this->logger
->debug( __METHOD__
. ": iterating over all container shards." );
639 [ , $shortCont, ] = self
::splitStoragePath( $params['dir'] );
640 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
641 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
642 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
650 * @see FileBackendStore::doClean()
651 * @stable to override
652 * @param string $container
654 * @param array $params
655 * @return StatusValue
657 protected function doCleanInternal( $container, $dir, array $params ) {
658 return $this->newStatus();
661 final public function fileExists( array $params ) {
662 /** @noinspection PhpUnusedLocalVariableInspection */
663 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
665 $stat = $this->getFileStat( $params );
666 if ( is_array( $stat ) ) {
670 return $stat === self
::RES_ABSENT ?
false : self
::EXISTENCE_ERROR
;
673 final public function getFileTimestamp( array $params ) {
674 /** @noinspection PhpUnusedLocalVariableInspection */
675 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
677 $stat = $this->getFileStat( $params );
678 if ( is_array( $stat ) ) {
679 return $stat['mtime'];
682 return self
::TIMESTAMP_FAIL
; // all failure cases
685 final public function getFileSize( array $params ) {
686 /** @noinspection PhpUnusedLocalVariableInspection */
687 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
689 $stat = $this->getFileStat( $params );
690 if ( is_array( $stat ) ) {
691 return $stat['size'];
694 return self
::SIZE_FAIL
; // all failure cases
697 final public function getFileStat( array $params ) {
698 /** @noinspection PhpUnusedLocalVariableInspection */
699 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
701 $path = self
::normalizeStoragePath( $params['src'] );
702 if ( $path === null ) {
703 return self
::STAT_ERROR
; // invalid storage path
706 // Whether to bypass cache except for process cache entries loaded directly from
707 // high consistency backend queries (caller handles any cache flushing and locking)
708 $latest = !empty( $params['latest'] );
709 // Whether to ignore cache entries missing the SHA-1 field for existing files
710 $requireSHA1 = !empty( $params['requireSHA1'] );
712 $stat = $this->cheapCache
->getField( $path, 'stat', self
::CACHE_TTL
);
713 // Load the persistent stat cache into process cache if needed
716 // File stat is not in process cache
718 // Key/value store backends might opportunistically set file stat process
719 // cache entries from object listings that do not include the SHA-1. In that
720 // case, loading the persistent stat cache will likely yield the SHA-1.
721 ( $requireSHA1 && is_array( $stat ) && !isset( $stat['sha1'] ) )
723 $this->primeFileCache( [ $path ] );
724 // Get any newly process-cached entry
725 $stat = $this->cheapCache
->getField( $path, 'stat', self
::CACHE_TTL
);
729 if ( is_array( $stat ) ) {
731 ( !$latest ||
!empty( $stat['latest'] ) ) &&
732 ( !$requireSHA1 ||
isset( $stat['sha1'] ) )
736 } elseif ( $stat === self
::ABSENT_LATEST
) {
737 return self
::STAT_ABSENT
;
738 } elseif ( $stat === self
::ABSENT_NORMAL
) {
740 return self
::STAT_ABSENT
;
744 // Load the file stat from the backend and update caches
745 $stat = $this->doGetFileStat( $params );
746 $this->ingestFreshFileStats( [ $path => $stat ], $latest );
748 if ( is_array( $stat ) ) {
752 return $stat === self
::RES_ERROR ? self
::STAT_ERROR
: self
::STAT_ABSENT
;
756 * Ingest file stat entries that just came from querying the backend (not cache)
758 * @param array<string,array|false|null> $stats Map of storage path => {@see doGetFileStat} result
759 * @param bool $latest Whether doGetFileStat()/doGetFileStatMulti() had the 'latest' flag
760 * @return bool Whether all files have non-error stat replies
762 final protected function ingestFreshFileStats( array $stats, $latest ) {
765 foreach ( $stats as $path => $stat ) {
766 if ( is_array( $stat ) ) {
767 // Strongly consistent backends might automatically set this flag
768 $stat['latest'] ??
= $latest;
770 $this->cheapCache
->setField( $path, 'stat', $stat );
771 if ( isset( $stat['sha1'] ) ) {
772 // Some backends store the SHA-1 hash as metadata
773 $this->cheapCache
->setField(
776 [ 'hash' => $stat['sha1'], 'latest' => $latest ]
779 if ( isset( $stat['xattr'] ) ) {
780 // Some backends store custom headers/metadata
781 $stat['xattr'] = self
::normalizeXAttributes( $stat['xattr'] );
782 $this->cheapCache
->setField(
785 [ 'map' => $stat['xattr'], 'latest' => $latest ]
788 // Update persistent cache (@TODO: set all entries in one batch)
789 $this->setFileCache( $path, $stat );
790 } elseif ( $stat === self
::RES_ABSENT
) {
791 $this->cheapCache
->setField(
794 $latest ? self
::ABSENT_LATEST
: self
::ABSENT_NORMAL
796 $this->cheapCache
->setField(
799 [ 'map' => self
::XATTRS_FAIL
, 'latest' => $latest ]
801 $this->cheapCache
->setField(
804 [ 'hash' => self
::SHA1_FAIL
, 'latest' => $latest ]
806 $this->logger
->debug(
807 __METHOD__
. ': File {path} does not exist',
812 $this->logger
->error(
813 __METHOD__
. ': Could not stat file {path}',
823 * @see FileBackendStore::getFileStat()
824 * @param array $params
825 * @return array|false|null
827 abstract protected function doGetFileStat( array $params );
829 public function getFileContentsMulti( array $params ) {
830 /** @noinspection PhpUnusedLocalVariableInspection */
831 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
833 $params = $this->setConcurrencyFlags( $params );
834 $contents = $this->doGetFileContentsMulti( $params );
835 foreach ( $contents as $path => $content ) {
836 if ( !is_string( $content ) ) {
837 $contents[$path] = self
::CONTENT_FAIL
; // used for all failure cases
845 * @see FileBackendStore::getFileContentsMulti()
846 * @stable to override
847 * @param array $params
848 * @return string[]|bool[]|null[] Map of (path => string, false (missing), or null (error))
850 protected function doGetFileContentsMulti( array $params ) {
852 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
853 if ( $fsFile instanceof FSFile
) {
854 AtEase
::suppressWarnings();
855 $content = file_get_contents( $fsFile->getPath() );
856 AtEase
::restoreWarnings();
857 $contents[$path] = is_string( $content ) ?
$content : self
::RES_ERROR
;
859 // self::RES_ERROR or self::RES_ABSENT
860 $contents[$path] = $fsFile;
867 final public function getFileXAttributes( array $params ) {
868 /** @noinspection PhpUnusedLocalVariableInspection */
869 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
871 $path = self
::normalizeStoragePath( $params['src'] );
872 if ( $path === null ) {
873 return self
::XATTRS_FAIL
; // invalid storage path
875 $latest = !empty( $params['latest'] ); // use latest data?
876 if ( $this->cheapCache
->hasField( $path, 'xattr', self
::CACHE_TTL
) ) {
877 $stat = $this->cheapCache
->getField( $path, 'xattr' );
878 // If we want the latest data, check that this cached
879 // value was in fact fetched with the latest available data.
880 if ( !$latest ||
$stat['latest'] ) {
884 $fields = $this->doGetFileXAttributes( $params );
885 if ( is_array( $fields ) ) {
886 $fields = self
::normalizeXAttributes( $fields );
887 $this->cheapCache
->setField(
890 [ 'map' => $fields, 'latest' => $latest ]
892 } elseif ( $fields === self
::RES_ABSENT
) {
893 $this->cheapCache
->setField(
896 [ 'map' => self
::XATTRS_FAIL
, 'latest' => $latest ]
899 $fields = self
::XATTRS_FAIL
; // used for all failure cases
906 * @see FileBackendStore::getFileXAttributes()
907 * @stable to override
908 * @param array $params
909 * @return array[][]|false|null Attributes, false (missing file), or null (error)
911 protected function doGetFileXAttributes( array $params ) {
912 return [ 'headers' => [], 'metadata' => [] ]; // not supported
915 final public function getFileSha1Base36( array $params ) {
916 /** @noinspection PhpUnusedLocalVariableInspection */
917 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
919 $path = self
::normalizeStoragePath( $params['src'] );
920 if ( $path === null ) {
921 return self
::SHA1_FAIL
; // invalid storage path
923 $latest = !empty( $params['latest'] ); // use latest data?
924 if ( $this->cheapCache
->hasField( $path, 'sha1', self
::CACHE_TTL
) ) {
925 $stat = $this->cheapCache
->getField( $path, 'sha1' );
926 // If we want the latest data, check that this cached
927 // value was in fact fetched with the latest available data.
928 if ( !$latest ||
$stat['latest'] ) {
929 return $stat['hash'];
932 $sha1 = $this->doGetFileSha1Base36( $params );
933 if ( is_string( $sha1 ) ) {
934 $this->cheapCache
->setField(
937 [ 'hash' => $sha1, 'latest' => $latest ]
939 } elseif ( $sha1 === self
::RES_ABSENT
) {
940 $this->cheapCache
->setField(
943 [ 'hash' => self
::SHA1_FAIL
, 'latest' => $latest ]
946 $sha1 = self
::SHA1_FAIL
; // used for all failure cases
953 * @see FileBackendStore::getFileSha1Base36()
954 * @stable to override
955 * @param array $params
956 * @return bool|string|null SHA1, false (missing file), or null (error)
958 protected function doGetFileSha1Base36( array $params ) {
959 $fsFile = $this->getLocalReference( $params );
960 if ( $fsFile instanceof FSFile
) {
961 $sha1 = $fsFile->getSha1Base36();
963 return is_string( $sha1 ) ?
$sha1 : self
::RES_ERROR
;
966 return $fsFile === self
::RES_ERROR ? self
::RES_ERROR
: self
::RES_ABSENT
;
969 final public function getFileProps( array $params ) {
970 /** @noinspection PhpUnusedLocalVariableInspection */
971 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
973 $fsFile = $this->getLocalReference( $params );
975 return $fsFile ?
$fsFile->getProps() : FSFile
::placeholderProps();
978 final public function getLocalReferenceMulti( array $params ) {
979 /** @noinspection PhpUnusedLocalVariableInspection */
980 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
982 $params = $this->setConcurrencyFlags( $params );
984 $fsFiles = []; // (path => FSFile)
985 $latest = !empty( $params['latest'] ); // use latest data?
986 // Reuse any files already in process cache...
987 foreach ( $params['srcs'] as $src ) {
988 $path = self
::normalizeStoragePath( $src );
989 if ( $path === null ) {
990 $fsFiles[$src] = self
::RES_ERROR
; // invalid storage path
991 } elseif ( $this->expensiveCache
->hasField( $path, 'localRef' ) ) {
992 $val = $this->expensiveCache
->getField( $path, 'localRef' );
993 // If we want the latest data, check that this cached
994 // value was in fact fetched with the latest available data.
995 if ( !$latest ||
$val['latest'] ) {
996 $fsFiles[$src] = $val['object'];
1000 // Fetch local references of any remaining files...
1001 $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
1002 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
1003 if ( $fsFile instanceof FSFile
) {
1004 $fsFiles[$path] = $fsFile;
1005 $this->expensiveCache
->setField(
1008 [ 'object' => $fsFile, 'latest' => $latest ]
1011 // self::RES_ERROR or self::RES_ABSENT
1012 $fsFiles[$path] = $fsFile;
1020 * @see FileBackendStore::getLocalReferenceMulti()
1021 * @stable to override
1022 * @param array $params
1023 * @return string[]|bool[]|null[] Map of (path => FSFile, false (missing), or null (error))
1025 protected function doGetLocalReferenceMulti( array $params ) {
1026 return $this->doGetLocalCopyMulti( $params );
1029 final public function getLocalCopyMulti( array $params ) {
1030 /** @noinspection PhpUnusedLocalVariableInspection */
1031 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1033 $params = $this->setConcurrencyFlags( $params );
1035 return $this->doGetLocalCopyMulti( $params );
1039 * @see FileBackendStore::getLocalCopyMulti()
1040 * @param array $params
1041 * @return string[]|bool[]|null[] Map of (path => TempFSFile, false (missing), or null (error))
1043 abstract protected function doGetLocalCopyMulti( array $params );
1046 * @see FileBackend::getFileHttpUrl()
1047 * @stable to override
1048 * @param array $params
1049 * @return string|null
1051 public function getFileHttpUrl( array $params ) {
1052 return self
::TEMPURL_ERROR
; // not supported
1055 public function addShellboxInputFile( BoxedCommand
$command, string $boxedName,
1058 $ref = $this->getLocalReference( [ 'src' => $params['src'] ] );
1059 if ( $ref === false ) {
1060 return $this->newStatus( 'backend-fail-notexists', $params['src'] );
1061 } elseif ( $ref === null ) {
1062 return $this->newStatus( 'backend-fail-read', $params['src'] );
1064 $file = $command->newInputFileFromFile( $ref->getPath() )
1065 ->userData( __CLASS__
, $ref );
1066 $command->inputFile( $boxedName, $file );
1067 return $this->newStatus();
1071 final public function streamFile( array $params ) {
1072 /** @noinspection PhpUnusedLocalVariableInspection */
1073 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1074 $status = $this->newStatus();
1076 // Always set some fields for subclass convenience
1077 $params['options'] ??
= [];
1078 $params['headers'] ??
= [];
1080 // Don't stream it out as text/html if there was a PHP error
1081 if ( ( empty( $params['headless'] ) ||
$params['headers'] ) && headers_sent() ) {
1082 print "Headers already sent, terminating.\n";
1083 $status->fatal( 'backend-fail-stream', $params['src'] );
1087 $status->merge( $this->doStreamFile( $params ) );
1093 * @see FileBackendStore::streamFile()
1094 * @stable to override
1095 * @param array $params
1096 * @return StatusValue
1098 protected function doStreamFile( array $params ) {
1099 $status = $this->newStatus();
1102 $flags |
= !empty( $params['headless'] ) ? HTTPFileStreamer
::STREAM_HEADLESS
: 0;
1103 $flags |
= !empty( $params['allowOB'] ) ? HTTPFileStreamer
::STREAM_ALLOW_OB
: 0;
1105 $fsFile = $this->getLocalReference( $params );
1107 $streamer = new HTTPFileStreamer(
1109 $this->getStreamerOptions()
1111 $res = $streamer->stream( $params['headers'], true, $params['options'], $flags );
1114 HTTPFileStreamer
::send404Message( $params['src'], $flags );
1118 $status->fatal( 'backend-fail-stream', $params['src'] );
1124 final public function directoryExists( array $params ) {
1125 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
1126 if ( $dir === null ) {
1127 return self
::EXISTENCE_ERROR
; // invalid storage path
1129 if ( $shard !== null ) { // confined to a single container/shard
1130 return $this->doDirectoryExists( $fullCont, $dir, $params );
1131 } else { // directory is on several shards
1132 $this->logger
->debug( __METHOD__
. ": iterating over all container shards." );
1133 [ , $shortCont, ] = self
::splitStoragePath( $params['dir'] );
1134 $res = false; // response
1135 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
1136 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
1137 if ( $exists === true ) {
1139 break; // found one!
1140 } elseif ( $exists === self
::RES_ERROR
) {
1141 $res = self
::EXISTENCE_ERROR
;
1150 * @see FileBackendStore::directoryExists()
1152 * @param string $container Resolved container name
1153 * @param string $dir Resolved path relative to container
1154 * @param array $params
1157 abstract protected function doDirectoryExists( $container, $dir, array $params );
1159 final public function getDirectoryList( array $params ) {
1160 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
1161 if ( $dir === null ) {
1162 return self
::EXISTENCE_ERROR
; // invalid storage path
1164 if ( $shard !== null ) {
1165 // File listing is confined to a single container/shard
1166 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
1168 $this->logger
->debug( __METHOD__
. ": iterating over all container shards." );
1169 // File listing spans multiple containers/shards
1170 [ , $shortCont, ] = self
::splitStoragePath( $params['dir'] );
1172 return new FileBackendStoreShardDirIterator( $this,
1173 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
1178 * Do not call this function from places outside FileBackend
1180 * @see FileBackendStore::getDirectoryList()
1182 * @param string $container Resolved container name
1183 * @param string $dir Resolved path relative to container
1184 * @param array $params
1185 * @return Traversable|array|null Iterable list or null (error)
1187 abstract public function getDirectoryListInternal( $container, $dir, array $params );
1189 final public function getFileList( array $params ) {
1190 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
1191 if ( $dir === null ) {
1192 return self
::LIST_ERROR
; // invalid storage path
1194 if ( $shard !== null ) {
1195 // File listing is confined to a single container/shard
1196 return $this->getFileListInternal( $fullCont, $dir, $params );
1198 $this->logger
->debug( __METHOD__
. ": iterating over all container shards." );
1199 // File listing spans multiple containers/shards
1200 [ , $shortCont, ] = self
::splitStoragePath( $params['dir'] );
1202 return new FileBackendStoreShardFileIterator( $this,
1203 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
1208 * Do not call this function from places outside FileBackend
1210 * @see FileBackendStore::getFileList()
1212 * @param string $container Resolved container name
1213 * @param string $dir Resolved path relative to container
1214 * @param array $params
1215 * @return Traversable|string[]|null Iterable list or null (error)
1217 abstract public function getFileListInternal( $container, $dir, array $params );
1220 * Return a list of FileOp objects from a list of operations.
1221 * Do not call this function from places outside FileBackend.
1223 * The result must have the same number of items as the input.
1224 * An exception is thrown if an unsupported operation is requested.
1226 * @param array[] $ops Same format as doOperations()
1228 * @throws FileBackendError
1230 final public function getOperationsInternal( array $ops ) {
1232 'store' => StoreFileOp
::class,
1233 'copy' => CopyFileOp
::class,
1234 'move' => MoveFileOp
::class,
1235 'delete' => DeleteFileOp
::class,
1236 'create' => CreateFileOp
::class,
1237 'describe' => DescribeFileOp
::class,
1238 'null' => NullFileOp
::class
1241 $performOps = []; // array of FileOp objects
1242 // Build up ordered array of FileOps...
1243 foreach ( $ops as $operation ) {
1244 $opName = $operation['op'];
1245 if ( isset( $supportedOps[$opName] ) ) {
1246 $class = $supportedOps[$opName];
1247 // Get params for this operation
1248 $params = $operation;
1249 // Append the FileOp class
1250 $performOps[] = new $class( $this, $params, $this->logger
);
1252 throw new FileBackendError( "Operation '$opName' is not supported." );
1260 * Get a list of storage paths to lock for a list of operations
1261 * Returns an array with LockManager::LOCK_UW (shared locks) and
1262 * LockManager::LOCK_EX (exclusive locks) keys, each corresponding
1263 * to a list of storage paths to be locked. All returned paths are
1266 * @param FileOp[] $performOps List of FileOp objects
1267 * @return string[][] (LockManager::LOCK_UW => path list, LockManager::LOCK_EX => path list)
1269 final public function getPathsToLockForOpsInternal( array $performOps ) {
1270 // Build up a list of files to lock...
1271 $paths = [ 'sh' => [], 'ex' => [] ];
1272 foreach ( $performOps as $fileOp ) {
1273 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1274 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1276 // Optimization: if doing an EX lock anyway, don't also set an SH one
1277 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1278 // Get a shared lock on the parent directory of each path changed
1279 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1282 LockManager
::LOCK_UW
=> $paths['sh'],
1283 LockManager
::LOCK_EX
=> $paths['ex']
1287 public function getScopedLocksForOps( array $ops, StatusValue
$status ) {
1288 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1290 return $this->getScopedFileLocks( $paths, 'mixed', $status );
1293 final protected function doOperationsInternal( array $ops, array $opts ) {
1294 /** @noinspection PhpUnusedLocalVariableInspection */
1295 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1296 $status = $this->newStatus();
1298 // Fix up custom header name/value pairs
1299 $ops = array_map( [ $this, 'sanitizeOpHeaders' ], $ops );
1300 // Build up a list of FileOps and involved paths
1301 $fileOps = $this->getOperationsInternal( $ops );
1303 foreach ( $fileOps as $fileOp ) {
1304 $pathsUsed = array_merge( $pathsUsed, $fileOp->storagePathsReadOrChanged() );
1307 // Acquire any locks as needed for the scope of this function
1308 if ( empty( $opts['nonLocking'] ) ) {
1309 $pathsByLockType = $this->getPathsToLockForOpsInternal( $fileOps );
1310 /** @noinspection PhpUnusedLocalVariableInspection */
1311 $scopeLock = $this->getScopedFileLocks( $pathsByLockType, 'mixed', $status );
1312 if ( !$status->isOK() ) {
1313 return $status; // abort
1317 // Clear any file cache entries (after locks acquired)
1318 if ( empty( $opts['preserveCache'] ) ) {
1319 $this->clearCache( $pathsUsed );
1322 // Enlarge the cache to fit the stat entries of these files
1323 $this->cheapCache
->setMaxSize( max( 2 * count( $pathsUsed ), self
::CACHE_CHEAP_SIZE
) );
1325 // Load from the persistent container caches
1326 $this->primeContainerCache( $pathsUsed );
1327 // Get the latest stat info for all the files (having locked them)
1328 $ok = $this->preloadFileStat( [ 'srcs' => $pathsUsed, 'latest' => true ] );
1331 // Actually attempt the operation batch...
1332 $opts = $this->setConcurrencyFlags( $opts );
1333 $subStatus = FileOpBatch
::attempt( $fileOps, $opts );
1335 // If we could not even stat some files, then bail out
1336 $subStatus = $this->newStatus( 'backend-fail-internal', $this->name
);
1337 foreach ( $ops as $i => $op ) { // mark each op as failed
1338 $subStatus->success
[$i] = false;
1339 ++
$subStatus->failCount
;
1341 $this->logger
->error( static::class . "-{$this->name} " .
1342 " stat failure; aborted operations: " . FormatJson
::encode( $ops ) );
1345 // Merge errors into StatusValue fields
1346 $status->merge( $subStatus );
1347 $status->success
= $subStatus->success
; // not done in merge()
1349 // Shrink the stat cache back to normal size
1350 $this->cheapCache
->setMaxSize( self
::CACHE_CHEAP_SIZE
);
1355 final protected function doQuickOperationsInternal( array $ops, array $opts ) {
1356 /** @noinspection PhpUnusedLocalVariableInspection */
1357 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1358 $status = $this->newStatus();
1360 // Fix up custom header name/value pairs
1361 $ops = array_map( [ $this, 'sanitizeOpHeaders' ], $ops );
1362 // Build up a list of FileOps and involved paths
1363 $fileOps = $this->getOperationsInternal( $ops );
1365 foreach ( $fileOps as $fileOp ) {
1366 $pathsUsed = array_merge( $pathsUsed, $fileOp->storagePathsReadOrChanged() );
1369 // Clear any file cache entries for involved paths
1370 $this->clearCache( $pathsUsed );
1372 // Parallel ops may be disabled in config due to dependencies (e.g. needing popen())
1373 $async = ( $this->parallelize
=== 'implicit' && count( $ops ) > 1 );
1374 $maxConcurrency = $this->concurrency
; // throttle
1375 /** @var StatusValue[] $statuses */
1376 $statuses = []; // array of (index => StatusValue)
1377 /** @var FileBackendStoreOpHandle[] $batch */
1379 foreach ( $fileOps as $index => $fileOp ) {
1381 ?
$fileOp->attemptAsyncQuick()
1382 : $fileOp->attemptQuick();
1383 if ( $subStatus->value
instanceof FileBackendStoreOpHandle
) { // async
1384 if ( count( $batch ) >= $maxConcurrency ) {
1385 // Execute this batch. Don't queue any more ops since they contain
1386 // open filehandles which are a limited resource (T230245).
1387 $statuses +
= $this->executeOpHandlesInternal( $batch );
1390 $batch[$index] = $subStatus->value
; // keep index
1391 } else { // error or completed
1392 $statuses[$index] = $subStatus; // keep index
1395 if ( count( $batch ) ) {
1396 $statuses +
= $this->executeOpHandlesInternal( $batch );
1398 // Marshall and merge all the responses...
1399 foreach ( $statuses as $index => $subStatus ) {
1400 $status->merge( $subStatus );
1401 if ( $subStatus->isOK() ) {
1402 $status->success
[$index] = true;
1403 ++
$status->successCount
;
1405 $status->success
[$index] = false;
1406 ++
$status->failCount
;
1410 $this->clearCache( $pathsUsed );
1416 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1417 * The resulting StatusValue object fields will correspond
1418 * to the order in which the handles where given.
1420 * @param FileBackendStoreOpHandle[] $fileOpHandles
1421 * @return StatusValue[] Map of StatusValue objects
1422 * @throws FileBackendError
1424 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1425 /** @noinspection PhpUnusedLocalVariableInspection */
1426 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1428 foreach ( $fileOpHandles as $fileOpHandle ) {
1429 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle
) ) {
1430 throw new InvalidArgumentException( "Expected FileBackendStoreOpHandle object." );
1431 } elseif ( $fileOpHandle->backend
->getName() !== $this->getName() ) {
1432 throw new InvalidArgumentException( "Expected handle for this file backend." );
1436 $statuses = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1437 foreach ( $fileOpHandles as $fileOpHandle ) {
1438 $fileOpHandle->closeResources();
1445 * @see FileBackendStore::executeOpHandlesInternal()
1446 * @stable to override
1448 * @param FileBackendStoreOpHandle[] $fileOpHandles
1450 * @throws FileBackendError
1451 * @return StatusValue[] List of corresponding StatusValue objects
1453 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1454 if ( count( $fileOpHandles ) ) {
1455 throw new FileBackendError( "Backend does not support asynchronous operations." );
1462 * Normalize and filter HTTP headers from a file operation
1464 * This normalizes and strips long HTTP headers from a file operation.
1465 * Most headers are just numbers, but some are allowed to be long.
1466 * This function is useful for cleaning up headers and avoiding backend
1467 * specific errors, especially in the middle of batch file operations.
1469 * @param array $op Same format as doOperation()
1472 protected function sanitizeOpHeaders( array $op ) {
1473 static $longs = [ 'content-disposition' ];
1475 if ( isset( $op['headers'] ) ) { // op sets HTTP headers
1477 foreach ( $op['headers'] as $name => $value ) {
1478 $name = strtolower( $name );
1479 $maxHVLen = in_array( $name, $longs ) ? INF
: 255;
1480 if ( strlen( $name ) > 255 ||
strlen( $value ) > $maxHVLen ) {
1481 $this->logger
->error( "Header '{header}' is too long.", [
1482 'filebackend' => $this->name
,
1483 'header' => "$name: $value",
1486 $newHeaders[$name] = strlen( $value ) ?
$value : ''; // null/false => ""
1489 $op['headers'] = $newHeaders;
1495 final public function preloadCache( array $paths ) {
1496 $fullConts = []; // full container names
1497 foreach ( $paths as $path ) {
1498 [ $fullCont, , ] = $this->resolveStoragePath( $path );
1499 $fullConts[] = $fullCont;
1501 // Load from the persistent file and container caches
1502 $this->primeContainerCache( $fullConts );
1503 $this->primeFileCache( $paths );
1506 final public function clearCache( ?
array $paths = null ) {
1507 if ( is_array( $paths ) ) {
1508 $paths = array_map( [ FileBackend
::class, 'normalizeStoragePath' ], $paths );
1509 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1511 if ( $paths === null ) {
1512 $this->cheapCache
->clear();
1513 $this->expensiveCache
->clear();
1515 foreach ( $paths as $path ) {
1516 $this->cheapCache
->clear( $path );
1517 $this->expensiveCache
->clear( $path );
1520 $this->doClearCache( $paths );
1524 * Clears any additional stat caches for storage paths
1525 * @stable to override
1527 * @see FileBackend::clearCache()
1529 * @param string[]|null $paths Storage paths (optional)
1531 protected function doClearCache( ?
array $paths = null ) {
1534 final public function preloadFileStat( array $params ) {
1535 /** @noinspection PhpUnusedLocalVariableInspection */
1536 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1538 $params['concurrency'] = ( $this->parallelize
!== 'off' ) ?
$this->concurrency
: 1;
1539 $stats = $this->doGetFileStatMulti( $params );
1540 if ( $stats === null ) {
1541 return true; // not supported
1544 // Whether this queried the backend in high consistency mode
1545 $latest = !empty( $params['latest'] );
1547 return $this->ingestFreshFileStats( $stats, $latest );
1551 * Get file stat information (concurrently if possible) for several files
1552 * @stable to override
1554 * @see FileBackend::getFileStat()
1556 * @param array $params Parameters include:
1557 * - srcs : list of source storage paths
1558 * - latest : use the latest available data
1559 * @return array<string,array|false|null>|null Null if not supported. Otherwise a map of storage
1560 * path to attribute map, false (missing file), or null (I/O error).
1563 protected function doGetFileStatMulti( array $params ) {
1564 return null; // not supported
1568 * Is this a key/value store where directories are just virtual?
1569 * Virtual directories exists in so much as files exists that are
1570 * prefixed with the directory path followed by a forward slash.
1574 abstract protected function directoriesAreVirtual();
1577 * Check if a short container name is valid
1579 * This checks for length and illegal characters.
1580 * This may disallow certain characters that can appear
1581 * in the prefix used to make the full container name.
1583 * @param string $container
1586 final protected static function isValidShortContainerName( $container ) {
1587 // Suffixes like '.xxx' (hex shard chars) or '.seg' (file segments)
1588 // might be used by subclasses. Reserve the dot character.
1589 // The only way dots end up in containers (e.g. resolveStoragePath)
1590 // is due to the wikiId container prefix or the above suffixes.
1591 return self
::isValidContainerName( $container ) && !preg_match( '/[.]/', $container );
1595 * Check if a full container name is valid
1597 * This checks for length and illegal characters.
1598 * Limiting the characters makes migrations to other stores easier.
1600 * @param string $container
1603 final protected static function isValidContainerName( $container ) {
1604 // This accounts for NTFS, Swift, and Ceph restrictions
1605 // and disallows directory separators or traversal characters.
1606 // Note that matching strings URL encode to the same string;
1607 // in Swift/Ceph, the length restriction is *after* URL encoding.
1608 return (bool)preg_match( '/^[a-z0-9][a-z0-9-_.]{0,199}$/i', $container );
1612 * Splits a storage path into an internal container name,
1613 * an internal relative file name, and a container shard suffix.
1614 * Any shard suffix is already appended to the internal container name.
1615 * This also checks that the storage path is valid and within this backend.
1617 * If the container is sharded but a suffix could not be determined,
1618 * this means that the path can only refer to a directory and can only
1619 * be scanned by looking in all the container shards.
1621 * @param string $storagePath
1622 * @return array (container, path, container suffix) or (null, null, null) if invalid
1624 final protected function resolveStoragePath( $storagePath ) {
1625 [ $backend, $shortCont, $relPath ] = self
::splitStoragePath( $storagePath );
1626 if ( $backend === $this->name
) { // must be for this backend
1627 $relPath = self
::normalizeContainerPath( $relPath );
1628 if ( $relPath !== null && self
::isValidShortContainerName( $shortCont ) ) {
1629 // Get shard for the normalized path if this container is sharded
1630 $cShard = $this->getContainerShard( $shortCont, $relPath );
1631 // Validate and sanitize the relative path (backend-specific)
1632 $relPath = $this->resolveContainerPath( $shortCont, $relPath );
1633 if ( $relPath !== null ) {
1634 // Prepend any domain ID prefix to the container name
1635 $container = $this->fullContainerName( $shortCont );
1636 if ( self
::isValidContainerName( $container ) ) {
1637 // Validate and sanitize the container name (backend-specific)
1638 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1639 if ( $container !== null ) {
1640 return [ $container, $relPath, $cShard ];
1647 return [ null, null, null ];
1651 * Like resolveStoragePath() except null values are returned if
1652 * the container is sharded and the shard could not be determined
1653 * or if the path ends with '/'. The latter case is illegal for FS
1654 * backends and can confuse listings for object store backends.
1656 * This function is used when resolving paths that must be valid
1657 * locations for files. Directory and listing functions should
1658 * generally just use resolveStoragePath() instead.
1660 * @see FileBackendStore::resolveStoragePath()
1662 * @param string $storagePath
1663 * @return array (container, path) or (null, null) if invalid
1665 final protected function resolveStoragePathReal( $storagePath ) {
1666 [ $container, $relPath, $cShard ] = $this->resolveStoragePath( $storagePath );
1667 if ( $cShard !== null && substr( $relPath, -1 ) !== '/' ) {
1668 return [ $container, $relPath ];
1671 return [ null, null ];
1675 * Get the container name shard suffix for a given path.
1676 * Any empty suffix means the container is not sharded.
1678 * @param string $container Container name
1679 * @param string $relPath Storage path relative to the container
1680 * @return string|null Returns null if shard could not be determined
1682 final protected function getContainerShard( $container, $relPath ) {
1683 [ $levels, $base, $repeat ] = $this->getContainerHashLevels( $container );
1684 if ( $levels == 1 ||
$levels == 2 ) {
1685 // Hash characters are either base 16 or 36
1686 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1687 // Get a regex that represents the shard portion of paths.
1688 // The concatenation of the captures gives us the shard.
1689 if ( $levels === 1 ) { // 16 or 36 shards per container
1690 $hashDirRegex = '(' . $char . ')';
1691 } else { // 256 or 1296 shards per container
1692 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1693 $hashDirRegex = $char . '/(' . $char . '{2})';
1694 } else { // short hash dir format (e.g. "a/b/c")
1695 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1698 // Allow certain directories to be above the hash dirs so as
1699 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1700 // They must be 2+ chars to avoid any hash directory ambiguity.
1702 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1703 return '.' . implode( '', array_slice( $m, 1 ) );
1706 return null; // failed to match
1709 return ''; // no sharding
1713 * Check if a storage path maps to a single shard.
1714 * Container dirs like "a", where the container shards on "x/xy",
1715 * can reside on several shards. Such paths are tricky to handle.
1717 * @param string $storagePath
1720 final public function isSingleShardPathInternal( $storagePath ) {
1721 [ , , $shard ] = $this->resolveStoragePath( $storagePath );
1723 return ( $shard !== null );
1727 * Get the sharding config for a container.
1728 * If greater than 0, then all file storage paths within
1729 * the container are required to be hashed accordingly.
1731 * @param string $container
1732 * @return array (integer levels, integer base, repeat flag) or (0, 0, false)
1734 final protected function getContainerHashLevels( $container ) {
1735 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1736 $config = $this->shardViaHashLevels
[$container];
1737 $hashLevels = (int)$config['levels'];
1738 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1739 $hashBase = (int)$config['base'];
1740 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1741 return [ $hashLevels, $hashBase, $config['repeat'] ];
1746 return [ 0, 0, false ]; // no sharding
1750 * Get a list of full container shard suffixes for a container
1752 * @param string $container
1755 final protected function getContainerSuffixes( $container ) {
1757 [ $digits, $base ] = $this->getContainerHashLevels( $container );
1758 if ( $digits > 0 ) {
1759 $numShards = $base ** $digits;
1760 for ( $index = 0; $index < $numShards; $index++
) {
1761 $shards[] = '.' . \Wikimedia\base_convert
( (string)$index, 10, $base, $digits );
1769 * Get the full container name, including the domain ID prefix
1771 * @param string $container
1774 final protected function fullContainerName( $container ) {
1775 if ( $this->domainId
!= '' ) {
1776 return "{$this->domainId}-$container";
1783 * Resolve a container name, checking if it's allowed by the backend.
1784 * This is intended for internal use, such as encoding illegal chars.
1785 * Subclasses can override this to be more restrictive.
1786 * @stable to override
1788 * @param string $container
1789 * @return string|null
1791 protected function resolveContainerName( $container ) {
1796 * Resolve a relative storage path, checking if it's allowed by the backend.
1797 * This is intended for internal use, such as encoding illegal chars or perhaps
1798 * getting absolute paths (e.g. FS based backends). Note that the relative path
1799 * may be the empty string (e.g. the path is simply to the container).
1800 * @stable to override
1802 * @param string $container Container name
1803 * @param string $relStoragePath Storage path relative to the container
1804 * @return string|null Path or null if not valid
1806 protected function resolveContainerPath( $container, $relStoragePath ) {
1807 return $relStoragePath;
1811 * Get the cache key for a container
1813 * @param string $container Resolved container name
1816 private function containerCacheKey( $container ) {
1817 return "filebackend:{$this->name}:{$this->domainId}:container:{$container}";
1821 * Set the cached info for a container
1823 * @param string $container Resolved container name
1824 * @param array $val Information to cache
1826 final protected function setContainerCache( $container, array $val ) {
1827 if ( !$this->memCache
->set( $this->containerCacheKey( $container ), $val, 14 * 86400 ) ) {
1828 $this->logger
->warning( "Unable to set stat cache for container {container}.",
1829 [ 'filebackend' => $this->name
, 'container' => $container ]
1835 * Delete the cached info for a container.
1836 * The cache key is salted for a while to prevent race conditions.
1838 * @param string $container Resolved container name
1840 final protected function deleteContainerCache( $container ) {
1841 if ( !$this->memCache
->delete( $this->containerCacheKey( $container ), 300 ) ) {
1842 $this->logger
->warning( "Unable to delete stat cache for container {container}.",
1843 [ 'filebackend' => $this->name
, 'container' => $container ]
1849 * Do a batch lookup from cache for container stats for all containers
1850 * used in a list of container names or storage paths objects.
1851 * This loads the persistent cache values into the process cache.
1853 * @param array $items
1855 final protected function primeContainerCache( array $items ) {
1856 /** @noinspection PhpUnusedLocalVariableInspection */
1857 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1859 $paths = []; // list of storage paths
1860 $contNames = []; // (cache key => resolved container name)
1861 // Get all the paths/containers from the items...
1862 foreach ( $items as $item ) {
1863 if ( self
::isStoragePath( $item ) ) {
1865 } elseif ( is_string( $item ) ) { // full container name
1866 $contNames[$this->containerCacheKey( $item )] = $item;
1869 // Get all the corresponding cache keys for paths...
1870 foreach ( $paths as $path ) {
1871 [ $fullCont, , ] = $this->resolveStoragePath( $path );
1872 if ( $fullCont !== null ) { // valid path for this backend
1873 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1877 $contInfo = []; // (resolved container name => cache value)
1878 // Get all cache entries for these container cache keys...
1879 $values = $this->memCache
->getMulti( array_keys( $contNames ) );
1880 foreach ( $values as $cacheKey => $val ) {
1881 $contInfo[$contNames[$cacheKey]] = $val;
1884 // Populate the container process cache for the backend...
1885 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1889 * Fill the backend-specific process cache given an array of
1890 * resolved container names and their corresponding cached info.
1891 * Only containers that actually exist should appear in the map.
1892 * @stable to override
1894 * @param array $containerInfo Map of resolved container names to cached info
1896 protected function doPrimeContainerCache( array $containerInfo ) {
1900 * Get the cache key for a file path
1902 * @param string $path Normalized storage path
1905 private function fileCacheKey( $path ) {
1906 return "filebackend:{$this->name}:{$this->domainId}:file:" . sha1( $path );
1910 * Set the cached stat info for a file path.
1911 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1912 * salting for the case when a file is created at a path were there was none before.
1914 * @param string $path Storage path
1915 * @param array $val Stat information to cache
1917 final protected function setFileCache( $path, array $val ) {
1918 $path = FileBackend
::normalizeStoragePath( $path );
1919 if ( $path === null ) {
1920 return; // invalid storage path
1922 $mtime = (int)ConvertibleTimestamp
::convert( TS_UNIX
, $val['mtime'] );
1923 $ttl = $this->memCache
->adaptiveTTL( $mtime, 7 * 86400, 300, 0.1 );
1924 $key = $this->fileCacheKey( $path );
1925 // Set the cache unless it is currently salted.
1926 if ( !$this->memCache
->set( $key, $val, $ttl ) ) {
1927 $this->logger
->warning( "Unable to set stat cache for file {path}.",
1928 [ 'filebackend' => $this->name
, 'path' => $path ]
1934 * Delete the cached stat info for a file path.
1935 * The cache key is salted for a while to prevent race conditions.
1936 * Since negatives (404s) are not cached, this does not need to be called when
1937 * a file is created at a path were there was none before.
1939 * @param string $path Storage path
1941 final protected function deleteFileCache( $path ) {
1942 $path = FileBackend
::normalizeStoragePath( $path );
1943 if ( $path === null ) {
1944 return; // invalid storage path
1946 if ( !$this->memCache
->delete( $this->fileCacheKey( $path ), 300 ) ) {
1947 $this->logger
->warning( "Unable to delete stat cache for file {path}.",
1948 [ 'filebackend' => $this->name
, 'path' => $path ]
1954 * Do a batch lookup from cache for file stats for all paths
1955 * used in a list of storage paths or FileOp objects.
1956 * This loads the persistent cache values into the process cache.
1958 * @param array $items List of storage paths
1960 final protected function primeFileCache( array $items ) {
1961 /** @noinspection PhpUnusedLocalVariableInspection */
1962 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1964 $paths = []; // list of storage paths
1965 $pathNames = []; // (cache key => storage path)
1966 // Get all the paths/containers from the items...
1967 foreach ( $items as $item ) {
1968 if ( self
::isStoragePath( $item ) ) {
1969 $path = FileBackend
::normalizeStoragePath( $item );
1970 if ( $path !== null ) {
1975 // Get all the corresponding cache keys for paths...
1976 foreach ( $paths as $path ) {
1977 [ , $rel, ] = $this->resolveStoragePath( $path );
1978 if ( $rel !== null ) { // valid path for this backend
1979 $pathNames[$this->fileCacheKey( $path )] = $path;
1982 // Get all cache entries for these file cache keys.
1983 // Note that negatives are not cached by getFileStat()/preloadFileStat().
1984 $values = $this->memCache
->getMulti( array_keys( $pathNames ) );
1985 // Load all of the results into process cache...
1986 foreach ( array_filter( $values, 'is_array' ) as $cacheKey => $stat ) {
1987 $path = $pathNames[$cacheKey];
1988 // This flag only applies to stat info loaded directly
1989 // from a high consistency backend query to the process cache
1990 unset( $stat['latest'] );
1992 $this->cheapCache
->setField( $path, 'stat', $stat );
1993 if ( isset( $stat['sha1'] ) && strlen( $stat['sha1'] ) == 31 ) {
1994 // Some backends store SHA-1 as metadata
1995 $this->cheapCache
->setField(
1998 [ 'hash' => $stat['sha1'], 'latest' => false ]
2001 if ( isset( $stat['xattr'] ) && is_array( $stat['xattr'] ) ) {
2002 // Some backends store custom headers/metadata
2003 $stat['xattr'] = self
::normalizeXAttributes( $stat['xattr'] );
2004 $this->cheapCache
->setField(
2007 [ 'map' => $stat['xattr'], 'latest' => false ]
2014 * Normalize file headers/metadata to the FileBackend::getFileXAttributes() format
2016 * @param array $xattr
2020 final protected static function normalizeXAttributes( array $xattr ) {
2021 $newXAttr = [ 'headers' => [], 'metadata' => [] ];
2023 foreach ( $xattr['headers'] as $name => $value ) {
2024 $newXAttr['headers'][strtolower( $name )] = $value;
2027 foreach ( $xattr['metadata'] as $name => $value ) {
2028 $newXAttr['metadata'][strtolower( $name )] = $value;
2035 * Set the 'concurrency' option from a list of operation options
2037 * @param array $opts Map of operation options
2040 final protected function setConcurrencyFlags( array $opts ) {
2041 $opts['concurrency'] = 1; // off
2042 if ( $this->parallelize
=== 'implicit' ) {
2043 if ( $opts['parallelize'] ??
true ) {
2044 $opts['concurrency'] = $this->concurrency
;
2046 } elseif ( $this->parallelize
=== 'explicit' ) {
2047 if ( !empty( $opts['parallelize'] ) ) {
2048 $opts['concurrency'] = $this->concurrency
;
2056 * Get the content type to use in HEAD/GET requests for a file
2057 * @stable to override
2059 * @param string $storagePath
2060 * @param string|null $content File data
2061 * @param string|null $fsPath File system path
2062 * @return string MIME type
2064 protected function getContentType( $storagePath, $content, $fsPath ) {
2065 if ( $this->mimeCallback
) {
2066 return call_user_func_array( $this->mimeCallback
, func_get_args() );
2069 $mime = ( $fsPath !== null ) ?
mime_content_type( $fsPath ) : false;
2070 return $mime ?
: 'unknown/unknown';
2074 /** @deprecated class alias since 1.43 */
2075 class_alias( FileBackendStore
::class, 'FileBackendStore' );