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 use Wikimedia\AtEase\AtEase
;
25 use Wikimedia\Timestamp\ConvertibleTimestamp
;
28 * @brief Base class for all backends using particular storage medium.
30 * This class defines the methods as abstract that subclasses must implement.
31 * Outside callers should *not* use functions with "Internal" in the name.
33 * The FileBackend operations are implemented using basic functions
34 * such as storeInternal(), copyInternal(), deleteInternal() and the like.
35 * This class is also responsible for path resolution and sanitization.
37 * @ingroup FileBackend
40 abstract class FileBackendStore
extends FileBackend
{
41 /** @var WANObjectCache */
45 /** @var MapCacheLRU Map of paths to small (RAM/disk) cache items */
46 protected $cheapCache;
47 /** @var MapCacheLRU Map of paths to large (RAM/disk) cache items */
48 protected $expensiveCache;
50 /** @var array Map of container names to sharding config */
51 protected $shardViaHashLevels = [];
53 /** @var callable Method to get the MIME type of files */
54 protected $mimeCallback;
56 protected $maxFileSize = 4294967296; // integer bytes (4GiB)
58 const CACHE_TTL
= 10; // integer; TTL in seconds for process cache entries
59 const CACHE_CHEAP_SIZE
= 500; // integer; max entries in "cheap cache"
60 const CACHE_EXPENSIVE_SIZE
= 5; // integer; max entries in "expensive cache"
62 /** @var false Idiom for "no result due to missing file" (since 1.34) */
63 protected static $RES_ABSENT = false;
64 /** @var null Idiom for "no result due to I/O errors" (since 1.34) */
65 protected static $RES_ERROR = null;
67 /** @var string File does not exist according to a normal stat query */
68 protected static $ABSENT_NORMAL = 'FNE-N';
69 /** @var string File does not exist according to a "latest"-mode stat query */
70 protected static $ABSENT_LATEST = 'FNE-L';
73 * @see FileBackend::__construct()
74 * Additional $config params include:
75 * - srvCache : BagOStuff cache to APC or the like.
76 * - wanCache : WANObjectCache object to use for persistent caching.
77 * - mimeCallback : Callback that takes (storage path, content, file system path) and
78 * returns the MIME type of the file or 'unknown/unknown'. The file
79 * system path parameter should be used if the content one is null.
81 * @param array $config
83 public function __construct( array $config ) {
84 parent
::__construct( $config );
85 $this->mimeCallback
= $config['mimeCallback'] ??
null;
86 $this->srvCache
= new EmptyBagOStuff(); // disabled by default
87 $this->memCache
= WANObjectCache
::newEmpty(); // disabled by default
88 $this->cheapCache
= new MapCacheLRU( self
::CACHE_CHEAP_SIZE
);
89 $this->expensiveCache
= new MapCacheLRU( self
::CACHE_EXPENSIVE_SIZE
);
93 * Get the maximum allowable file size given backend
94 * medium restrictions and basic performance constraints.
95 * Do not call this function from places outside FileBackend and FileOp.
99 final public function maxFileSizeInternal() {
100 return $this->maxFileSize
;
104 * Check if a file can be created or changed at a given storage path in the backend
106 * FS backends should check that the parent directory exists, files can be written
107 * under it, and that any file already there is both readable and writable.
108 * Backends using key/value stores should check if the container exists.
110 * @param string $storagePath
113 abstract public function isPathUsableInternal( $storagePath );
116 * Create a file in the backend with the given contents.
117 * This will overwrite any file that exists at the destination.
118 * Do not call this function from places outside FileBackend and FileOp.
121 * - content : the raw file contents
122 * - dst : destination storage path
123 * - headers : HTTP header name/value map
124 * - async : StatusValue will be returned immediately if supported.
125 * If the StatusValue is OK, then its value field will be
126 * set to a FileBackendStoreOpHandle object.
127 * - dstExists : Whether a file exists at the destination (optimization).
128 * Callers can use "false" if no existing file is being changed.
130 * @param array $params
131 * @return StatusValue
133 final public function createInternal( array $params ) {
134 /** @noinspection PhpUnusedLocalVariableInspection */
135 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
137 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
138 $status = $this->newStatus( 'backend-fail-maxsize',
139 $params['dst'], $this->maxFileSizeInternal() );
141 $status = $this->doCreateInternal( $params );
142 $this->clearCache( [ $params['dst'] ] );
143 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
144 $this->deleteFileCache( $params['dst'] ); // persistent cache
152 * @see FileBackendStore::createInternal()
153 * @param array $params
154 * @return StatusValue
156 abstract protected function doCreateInternal( array $params );
159 * Store a file into the backend from a file on disk.
160 * This will overwrite any file that exists at the destination.
161 * Do not call this function from places outside FileBackend and FileOp.
164 * - src : source path on disk
165 * - dst : destination storage path
166 * - headers : HTTP header name/value map
167 * - async : StatusValue will be returned immediately if supported.
168 * If the StatusValue is OK, then its value field will be
169 * set to a FileBackendStoreOpHandle object.
170 * - dstExists : Whether a file exists at the destination (optimization).
171 * Callers can use "false" if no existing file is being changed.
173 * @param array $params
174 * @return StatusValue
176 final public function storeInternal( array $params ) {
177 /** @noinspection PhpUnusedLocalVariableInspection */
178 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
180 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
181 $status = $this->newStatus( 'backend-fail-maxsize',
182 $params['dst'], $this->maxFileSizeInternal() );
184 $status = $this->doStoreInternal( $params );
185 $this->clearCache( [ $params['dst'] ] );
186 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
187 $this->deleteFileCache( $params['dst'] ); // persistent cache
195 * @see FileBackendStore::storeInternal()
196 * @param array $params
197 * @return StatusValue
199 abstract protected function doStoreInternal( array $params );
202 * Copy a file from one storage path to another in the backend.
203 * This will overwrite any file that exists at the destination.
204 * Do not call this function from places outside FileBackend and FileOp.
207 * - src : source storage path
208 * - dst : destination storage path
209 * - ignoreMissingSource : do nothing if the source file does not exist
210 * - headers : HTTP header name/value map
211 * - async : StatusValue will be returned immediately if supported.
212 * If the StatusValue is OK, then its value field will be
213 * set to a FileBackendStoreOpHandle object.
214 * - dstExists : Whether a file exists at the destination (optimization).
215 * Callers can use "false" if no existing file is being changed.
217 * @param array $params
218 * @return StatusValue
220 final public function copyInternal( array $params ) {
221 /** @noinspection PhpUnusedLocalVariableInspection */
222 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
224 $status = $this->doCopyInternal( $params );
225 $this->clearCache( [ $params['dst'] ] );
226 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
227 $this->deleteFileCache( $params['dst'] ); // persistent cache
234 * @see FileBackendStore::copyInternal()
235 * @param array $params
236 * @return StatusValue
238 abstract protected function doCopyInternal( array $params );
241 * Delete a file at the storage path.
242 * Do not call this function from places outside FileBackend and FileOp.
245 * - src : source storage path
246 * - ignoreMissingSource : do nothing if the source file does not exist
247 * - async : StatusValue will be returned immediately if supported.
248 * If the StatusValue is OK, then its value field will be
249 * set to a FileBackendStoreOpHandle object.
251 * @param array $params
252 * @return StatusValue
254 final public function deleteInternal( array $params ) {
255 /** @noinspection PhpUnusedLocalVariableInspection */
256 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
258 $status = $this->doDeleteInternal( $params );
259 $this->clearCache( [ $params['src'] ] );
260 $this->deleteFileCache( $params['src'] ); // persistent cache
265 * @see FileBackendStore::deleteInternal()
266 * @param array $params
267 * @return StatusValue
269 abstract protected function doDeleteInternal( array $params );
272 * Move a file from one storage path to another in the backend.
273 * This will overwrite any file that exists at the destination.
274 * Do not call this function from places outside FileBackend and FileOp.
277 * - src : source storage path
278 * - dst : destination storage path
279 * - ignoreMissingSource : do nothing if the source file does not exist
280 * - headers : HTTP header name/value map
281 * - async : StatusValue will be returned immediately if supported.
282 * If the StatusValue is OK, then its value field will be
283 * set to a FileBackendStoreOpHandle object.
284 * - dstExists : Whether a file exists at the destination (optimization).
285 * Callers can use "false" if no existing file is being changed.
287 * @param array $params
288 * @return StatusValue
290 final public function moveInternal( array $params ) {
291 /** @noinspection PhpUnusedLocalVariableInspection */
292 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
294 $status = $this->doMoveInternal( $params );
295 $this->clearCache( [ $params['src'], $params['dst'] ] );
296 $this->deleteFileCache( $params['src'] ); // persistent cache
297 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
298 $this->deleteFileCache( $params['dst'] ); // persistent cache
305 * @see FileBackendStore::moveInternal()
306 * @param array $params
307 * @return StatusValue
309 protected function doMoveInternal( array $params ) {
310 unset( $params['async'] ); // two steps, won't work here :)
311 $nsrc = FileBackend
::normalizeStoragePath( $params['src'] );
312 $ndst = FileBackend
::normalizeStoragePath( $params['dst'] );
313 // Copy source to dest
314 $status = $this->copyInternal( $params );
315 if ( $nsrc !== $ndst && $status->isOK() ) {
316 // Delete source (only fails due to races or network problems)
317 $status->merge( $this->deleteInternal( [ 'src' => $params['src'] ] ) );
318 $status->setResult( true, $status->value
); // ignore delete() errors
325 * Alter metadata for a file at the storage path.
326 * Do not call this function from places outside FileBackend and FileOp.
329 * - src : source storage path
330 * - headers : HTTP header name/value map
331 * - async : StatusValue will be returned immediately if supported.
332 * If the StatusValue is OK, then its value field will be
333 * set to a FileBackendStoreOpHandle object.
335 * @param array $params
336 * @return StatusValue
338 final public function describeInternal( array $params ) {
339 /** @noinspection PhpUnusedLocalVariableInspection */
340 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
342 if ( count( $params['headers'] ) ) {
343 $status = $this->doDescribeInternal( $params );
344 $this->clearCache( [ $params['src'] ] );
345 $this->deleteFileCache( $params['src'] ); // persistent cache
347 $status = $this->newStatus(); // nothing to do
354 * @see FileBackendStore::describeInternal()
355 * @param array $params
356 * @return StatusValue
358 protected function doDescribeInternal( array $params ) {
359 return $this->newStatus();
363 * No-op file operation that does nothing.
364 * Do not call this function from places outside FileBackend and FileOp.
366 * @param array $params
367 * @return StatusValue
369 final public function nullInternal( array $params ) {
370 return $this->newStatus();
373 final public function concatenate( array $params ) {
374 /** @noinspection PhpUnusedLocalVariableInspection */
375 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
376 $status = $this->newStatus();
378 // Try to lock the source files for the scope of this function
379 /** @noinspection PhpUnusedLocalVariableInspection */
380 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager
::LOCK_UW
, $status );
381 if ( $status->isOK() ) {
382 // Actually do the file concatenation...
383 $start_time = microtime( true );
384 $status->merge( $this->doConcatenate( $params ) );
385 $sec = microtime( true ) - $start_time;
386 if ( !$status->isOK() ) {
387 $this->logger
->error( static::class . "-{$this->name}" .
388 " failed to concatenate " . count( $params['srcs'] ) . " file(s) [$sec sec]" );
396 * @see FileBackendStore::concatenate()
397 * @param array $params
398 * @return StatusValue
400 protected function doConcatenate( array $params ) {
401 $status = $this->newStatus();
402 $tmpPath = $params['dst']; // convenience
403 unset( $params['latest'] ); // sanity
405 // Check that the specified temp file is valid...
406 AtEase
::suppressWarnings();
407 $ok = ( is_file( $tmpPath ) && filesize( $tmpPath ) == 0 );
408 AtEase
::restoreWarnings();
409 if ( !$ok ) { // not present or not empty
410 $status->fatal( 'backend-fail-opentemp', $tmpPath );
415 // Get local FS versions of the chunks needed for the concatenation...
416 $fsFiles = $this->getLocalReferenceMulti( $params );
417 foreach ( $fsFiles as $path => &$fsFile ) {
418 if ( !$fsFile ) { // chunk failed to download?
419 $fsFile = $this->getLocalReference( [ 'src' => $path ] );
420 if ( !$fsFile ) { // retry failed?
421 $status->fatal( 'backend-fail-read', $path );
427 unset( $fsFile ); // unset reference so we can reuse $fsFile
429 // Get a handle for the destination temp file
430 $tmpHandle = fopen( $tmpPath, 'ab' );
431 if ( $tmpHandle === false ) {
432 $status->fatal( 'backend-fail-opentemp', $tmpPath );
437 // Build up the temp file using the source chunks (in order)...
438 foreach ( $fsFiles as $virtualSource => $fsFile ) {
439 // Get a handle to the local FS version
440 $sourceHandle = fopen( $fsFile->getPath(), 'rb' );
441 if ( $sourceHandle === false ) {
442 fclose( $tmpHandle );
443 $status->fatal( 'backend-fail-read', $virtualSource );
447 // Append chunk to file (pass chunk size to avoid magic quotes)
448 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
449 fclose( $sourceHandle );
450 fclose( $tmpHandle );
451 $status->fatal( 'backend-fail-writetemp', $tmpPath );
455 fclose( $sourceHandle );
457 if ( !fclose( $tmpHandle ) ) {
458 $status->fatal( 'backend-fail-closetemp', $tmpPath );
463 clearstatcache(); // temp file changed
468 final protected function doPrepare( array $params ) {
469 /** @noinspection PhpUnusedLocalVariableInspection */
470 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
471 $status = $this->newStatus();
473 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
474 if ( $dir === null ) {
475 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
477 return $status; // invalid storage path
480 if ( $shard !== null ) { // confined to a single container/shard
481 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
482 } else { // directory is on several shards
483 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
484 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
485 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
486 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
494 * @see FileBackendStore::doPrepare()
495 * @param string $container
497 * @param array $params
498 * @return StatusValue
500 protected function doPrepareInternal( $container, $dir, array $params ) {
501 return $this->newStatus();
504 final protected function doSecure( array $params ) {
505 /** @noinspection PhpUnusedLocalVariableInspection */
506 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
507 $status = $this->newStatus();
509 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
510 if ( $dir === null ) {
511 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
513 return $status; // invalid storage path
516 if ( $shard !== null ) { // confined to a single container/shard
517 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
518 } else { // directory is on several shards
519 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
520 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
521 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
522 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
530 * @see FileBackendStore::doSecure()
531 * @param string $container
533 * @param array $params
534 * @return StatusValue
536 protected function doSecureInternal( $container, $dir, array $params ) {
537 return $this->newStatus();
540 final protected function doPublish( array $params ) {
541 /** @noinspection PhpUnusedLocalVariableInspection */
542 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
543 $status = $this->newStatus();
545 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
546 if ( $dir === null ) {
547 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
549 return $status; // invalid storage path
552 if ( $shard !== null ) { // confined to a single container/shard
553 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
554 } else { // directory is on several shards
555 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
556 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
557 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
558 $status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
566 * @see FileBackendStore::doPublish()
567 * @param string $container
569 * @param array $params
570 * @return StatusValue
572 protected function doPublishInternal( $container, $dir, array $params ) {
573 return $this->newStatus();
576 final protected function doClean( array $params ) {
577 /** @noinspection PhpUnusedLocalVariableInspection */
578 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
579 $status = $this->newStatus();
581 // Recursive: first delete all empty subdirs recursively
582 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
583 $subDirsRel = $this->getTopDirectoryList( [ 'dir' => $params['dir'] ] );
584 if ( $subDirsRel !== null ) { // no errors
585 foreach ( $subDirsRel as $subDirRel ) {
586 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
587 $status->merge( $this->doClean( [ 'dir' => $subDir ] +
$params ) );
589 unset( $subDirsRel ); // free directory for rmdir() on Windows (for FS backends)
593 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
594 if ( $dir === null ) {
595 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
597 return $status; // invalid storage path
600 // Attempt to lock this directory...
601 $filesLockEx = [ $params['dir'] ];
602 /** @noinspection PhpUnusedLocalVariableInspection */
603 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
604 if ( !$status->isOK() ) {
605 return $status; // abort
608 if ( $shard !== null ) { // confined to a single container/shard
609 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
610 $this->deleteContainerCache( $fullCont ); // purge cache
611 } else { // directory is on several shards
612 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
613 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
614 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
615 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
616 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
624 * @see FileBackendStore::doClean()
625 * @param string $container
627 * @param array $params
628 * @return StatusValue
630 protected function doCleanInternal( $container, $dir, array $params ) {
631 return $this->newStatus();
634 final public function fileExists( array $params ) {
635 /** @noinspection PhpUnusedLocalVariableInspection */
636 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
638 $stat = $this->getFileStat( $params );
639 if ( is_array( $stat ) ) {
643 return ( $stat === self
::$RES_ABSENT ) ?
false : self
::EXISTENCE_ERROR
;
646 final public function getFileTimestamp( array $params ) {
647 /** @noinspection PhpUnusedLocalVariableInspection */
648 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
650 $stat = $this->getFileStat( $params );
651 if ( is_array( $stat ) ) {
652 return $stat['mtime'];
655 return self
::TIMESTAMP_FAIL
; // all failure cases
658 final public function getFileSize( array $params ) {
659 /** @noinspection PhpUnusedLocalVariableInspection */
660 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
662 $stat = $this->getFileStat( $params );
663 if ( is_array( $stat ) ) {
664 return $stat['size'];
667 return self
::SIZE_FAIL
; // all failure cases
670 final public function getFileStat( array $params ) {
671 /** @noinspection PhpUnusedLocalVariableInspection */
672 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
674 $path = self
::normalizeStoragePath( $params['src'] );
675 if ( $path === null ) {
676 return self
::STAT_ERROR
; // invalid storage path
679 // Whether to bypass cache except for process cache entries loaded directly from
680 // high consistency backend queries (caller handles any cache flushing and locking)
681 $latest = !empty( $params['latest'] );
682 // Whether to ignore cache entries missing the SHA-1 field for existing files
683 $requireSHA1 = !empty( $params['requireSHA1'] );
685 $stat = $this->cheapCache
->getField( $path, 'stat', self
::CACHE_TTL
);
686 // Load the persistent stat cache into process cache if needed
689 // File stat is not in process cache
691 // Key/value store backends might opportunistically set file stat process
692 // cache entries from object listings that do not include the SHA-1. In that
693 // case, loading the persistent stat cache will likely yield the SHA-1.
694 ( $requireSHA1 && is_array( $stat ) && !isset( $stat['sha1'] ) )
696 $this->primeFileCache( [ $path ] );
697 // Get any newly process-cached entry
698 $stat = $this->cheapCache
->getField( $path, 'stat', self
::CACHE_TTL
);
702 if ( is_array( $stat ) ) {
704 ( !$latest ||
$stat['latest'] ) &&
705 ( !$requireSHA1 ||
isset( $stat['sha1'] ) )
709 } elseif ( $stat === self
::$ABSENT_LATEST ) {
710 return self
::STAT_ABSENT
;
711 } elseif ( $stat === self
::$ABSENT_NORMAL ) {
713 return self
::STAT_ABSENT
;
717 // Load the file stat from the backend and update caches
718 $stat = $this->doGetFileStat( $params );
719 $this->ingestFreshFileStats( [ $path => $stat ], $latest );
721 if ( is_array( $stat ) ) {
725 return ( $stat === self
::$RES_ERROR ) ? self
::STAT_ERROR
: self
::STAT_ABSENT
;
729 * Ingest file stat entries that just came from querying the backend (not cache)
731 * @param array[]|bool[]|null[] $stats Map of (path => doGetFileStat() stype result)
732 * @param bool $latest Whether doGetFileStat()/doGetFileStatMulti() had the 'latest' flag
733 * @return bool Whether all files have non-error stat replies
735 final protected function ingestFreshFileStats( array $stats, $latest ) {
738 foreach ( $stats as $path => $stat ) {
739 if ( is_array( $stat ) ) {
740 // Strongly consistent backends might automatically set this flag
741 $stat['latest'] = $stat['latest'] ??
$latest;
743 $this->cheapCache
->setField( $path, 'stat', $stat );
744 if ( isset( $stat['sha1'] ) ) {
745 // Some backends store the SHA-1 hash as metadata
746 $this->cheapCache
->setField(
749 [ 'hash' => $stat['sha1'], 'latest' => $latest ]
752 if ( isset( $stat['xattr'] ) ) {
753 // Some backends store custom headers/metadata
754 $stat['xattr'] = self
::normalizeXAttributes( $stat['xattr'] );
755 $this->cheapCache
->setField(
758 [ 'map' => $stat['xattr'], 'latest' => $latest ]
761 // Update persistent cache (@TODO: set all entries in one batch)
762 $this->setFileCache( $path, $stat );
763 } elseif ( $stat === self
::$RES_ABSENT ) {
764 $this->cheapCache
->setField(
767 $latest ? self
::$ABSENT_LATEST : self
::$ABSENT_NORMAL
769 $this->cheapCache
->setField(
772 [ 'map' => self
::XATTRS_FAIL
, 'latest' => $latest ]
774 $this->cheapCache
->setField(
777 [ 'hash' => self
::SHA1_FAIL
, 'latest' => $latest ]
779 $this->logger
->debug(
780 __METHOD__
. ': File {path} does not exist',
785 $this->logger
->error(
786 __METHOD__
. ': Could not stat file {path}',
796 * @see FileBackendStore::getFileStat()
797 * @param array $params
799 abstract protected function doGetFileStat( array $params );
801 public function getFileContentsMulti( array $params ) {
802 /** @noinspection PhpUnusedLocalVariableInspection */
803 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
805 $params = $this->setConcurrencyFlags( $params );
806 $contents = $this->doGetFileContentsMulti( $params );
807 foreach ( $contents as $path => $content ) {
808 if ( !is_string( $content ) ) {
809 $contents[$path] = self
::CONTENT_FAIL
; // used for all failure cases
817 * @see FileBackendStore::getFileContentsMulti()
818 * @param array $params
819 * @return string[]|bool[]|null[] Map of (path => string, false (missing), or null (error))
821 protected function doGetFileContentsMulti( array $params ) {
823 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
824 if ( $fsFile instanceof FSFile
) {
825 AtEase
::suppressWarnings();
826 $content = file_get_contents( $fsFile->getPath() );
827 AtEase
::restoreWarnings();
828 $contents[$path] = is_string( $content ) ?
$content : self
::$RES_ERROR;
829 } elseif ( $fsFile === self
::$RES_ABSENT ) {
830 $contents[$path] = self
::$RES_ABSENT;
832 $contents[$path] = self
::$RES_ERROR;
839 final public function getFileXAttributes( array $params ) {
840 /** @noinspection PhpUnusedLocalVariableInspection */
841 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
843 $path = self
::normalizeStoragePath( $params['src'] );
844 if ( $path === null ) {
845 return self
::XATTRS_FAIL
; // invalid storage path
847 $latest = !empty( $params['latest'] ); // use latest data?
848 if ( $this->cheapCache
->hasField( $path, 'xattr', self
::CACHE_TTL
) ) {
849 $stat = $this->cheapCache
->getField( $path, 'xattr' );
850 // If we want the latest data, check that this cached
851 // value was in fact fetched with the latest available data.
852 if ( !$latest ||
$stat['latest'] ) {
856 $fields = $this->doGetFileXAttributes( $params );
857 if ( is_array( $fields ) ) {
858 $fields = self
::normalizeXAttributes( $fields );
859 $this->cheapCache
->setField(
862 [ 'map' => $fields, 'latest' => $latest ]
864 } elseif ( $fields === self
::$RES_ABSENT ) {
865 $this->cheapCache
->setField(
868 [ 'map' => self
::XATTRS_FAIL
, 'latest' => $latest ]
871 $fields = self
::XATTRS_FAIL
; // used for all failure cases
878 * @see FileBackendStore::getFileXAttributes()
879 * @param array $params
880 * @return array[][]|false|null Attributes, false (missing file), or null (error)
882 protected function doGetFileXAttributes( array $params ) {
883 return [ 'headers' => [], 'metadata' => [] ]; // not supported
886 final public function getFileSha1Base36( array $params ) {
887 /** @noinspection PhpUnusedLocalVariableInspection */
888 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
890 $path = self
::normalizeStoragePath( $params['src'] );
891 if ( $path === null ) {
892 return self
::SHA1_FAIL
; // invalid storage path
894 $latest = !empty( $params['latest'] ); // use latest data?
895 if ( $this->cheapCache
->hasField( $path, 'sha1', self
::CACHE_TTL
) ) {
896 $stat = $this->cheapCache
->getField( $path, 'sha1' );
897 // If we want the latest data, check that this cached
898 // value was in fact fetched with the latest available data.
899 if ( !$latest ||
$stat['latest'] ) {
900 return $stat['hash'];
903 $sha1 = $this->doGetFileSha1Base36( $params );
904 if ( is_string( $sha1 ) ) {
905 $this->cheapCache
->setField(
908 [ 'hash' => $sha1, 'latest' => $latest ]
910 } elseif ( $sha1 === self
::$RES_ABSENT ) {
911 $this->cheapCache
->setField(
914 [ 'hash' => self
::SHA1_FAIL
, 'latest' => $latest ]
917 $sha1 = self
::SHA1_FAIL
; // used for all failure cases
924 * @see FileBackendStore::getFileSha1Base36()
925 * @param array $params
926 * @return bool|string|null SHA1, false (missing file), or null (error)
928 protected function doGetFileSha1Base36( array $params ) {
929 $fsFile = $this->getLocalReference( $params );
930 if ( $fsFile instanceof FSFile
) {
931 $sha1 = $fsFile->getSha1Base36();
933 return is_string( $sha1 ) ?
$sha1 : self
::$RES_ERROR;
936 return ( $fsFile === self
::$RES_ERROR ) ? self
::$RES_ERROR : self
::$RES_ABSENT;
939 final public function getFileProps( array $params ) {
940 /** @noinspection PhpUnusedLocalVariableInspection */
941 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
943 $fsFile = $this->getLocalReference( $params );
945 return $fsFile ?
$fsFile->getProps() : FSFile
::placeholderProps();
948 final public function getLocalReferenceMulti( array $params ) {
949 /** @noinspection PhpUnusedLocalVariableInspection */
950 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
952 $params = $this->setConcurrencyFlags( $params );
954 $fsFiles = []; // (path => FSFile)
955 $latest = !empty( $params['latest'] ); // use latest data?
956 // Reuse any files already in process cache...
957 foreach ( $params['srcs'] as $src ) {
958 $path = self
::normalizeStoragePath( $src );
959 if ( $path === null ) {
960 $fsFiles[$src] = null; // invalid storage path
961 } elseif ( $this->expensiveCache
->hasField( $path, 'localRef' ) ) {
962 $val = $this->expensiveCache
->getField( $path, 'localRef' );
963 // If we want the latest data, check that this cached
964 // value was in fact fetched with the latest available data.
965 if ( !$latest ||
$val['latest'] ) {
966 $fsFiles[$src] = $val['object'];
970 // Fetch local references of any remaning files...
971 $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
972 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
973 if ( $fsFile instanceof FSFile
) {
974 $fsFiles[$path] = $fsFile;
975 $this->expensiveCache
->setField(
978 [ 'object' => $fsFile, 'latest' => $latest ]
981 $fsFiles[$path] = null; // used for all failure cases
989 * @see FileBackendStore::getLocalReferenceMulti()
990 * @param array $params
991 * @return string[]|bool[]|null[] Map of (path => FSFile, false (missing), or null (error))
993 protected function doGetLocalReferenceMulti( array $params ) {
994 return $this->doGetLocalCopyMulti( $params );
997 final public function getLocalCopyMulti( array $params ) {
998 /** @noinspection PhpUnusedLocalVariableInspection */
999 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1001 $params = $this->setConcurrencyFlags( $params );
1002 $tmpFiles = $this->doGetLocalCopyMulti( $params );
1003 foreach ( $tmpFiles as $path => $tmpFile ) {
1005 $tmpFiles[$path] = null; // used for all failure cases
1013 * @see FileBackendStore::getLocalCopyMulti()
1014 * @param array $params
1015 * @return string[]|bool[]|null[] Map of (path => TempFSFile, false (missing), or null (error))
1017 abstract protected function doGetLocalCopyMulti( array $params );
1020 * @see FileBackend::getFileHttpUrl()
1021 * @param array $params
1022 * @return string|null
1024 public function getFileHttpUrl( array $params ) {
1025 return self
::TEMPURL_ERROR
; // not supported
1028 final public function streamFile( array $params ) {
1029 /** @noinspection PhpUnusedLocalVariableInspection */
1030 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1031 $status = $this->newStatus();
1033 // Always set some fields for subclass convenience
1034 $params['options'] = $params['options'] ??
[];
1035 $params['headers'] = $params['headers'] ??
[];
1037 // Don't stream it out as text/html if there was a PHP error
1038 if ( ( empty( $params['headless'] ) ||
$params['headers'] ) && headers_sent() ) {
1039 print "Headers already sent, terminating.\n";
1040 $status->fatal( 'backend-fail-stream', $params['src'] );
1044 $status->merge( $this->doStreamFile( $params ) );
1050 * @see FileBackendStore::streamFile()
1051 * @param array $params
1052 * @return StatusValue
1054 protected function doStreamFile( array $params ) {
1055 $status = $this->newStatus();
1058 $flags |
= !empty( $params['headless'] ) ? HTTPFileStreamer
::STREAM_HEADLESS
: 0;
1059 $flags |
= !empty( $params['allowOB'] ) ? HTTPFileStreamer
::STREAM_ALLOW_OB
: 0;
1061 $fsFile = $this->getLocalReference( $params );
1063 $streamer = new HTTPFileStreamer(
1066 'obResetFunc' => $this->obResetFunc
,
1067 'streamMimeFunc' => $this->streamMimeFunc
1070 $res = $streamer->stream( $params['headers'], true, $params['options'], $flags );
1073 HTTPFileStreamer
::send404Message( $params['src'], $flags );
1077 $status->fatal( 'backend-fail-stream', $params['src'] );
1083 final public function directoryExists( array $params ) {
1084 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
1085 if ( $dir === null ) {
1086 return self
::EXISTENCE_ERROR
; // invalid storage path
1088 if ( $shard !== null ) { // confined to a single container/shard
1089 return $this->doDirectoryExists( $fullCont, $dir, $params );
1090 } else { // directory is on several shards
1091 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
1092 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
1093 $res = false; // response
1094 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
1095 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
1096 if ( $exists === true ) {
1098 break; // found one!
1099 } elseif ( $exists === self
::$RES_ERROR ) {
1100 $res = self
::EXISTENCE_ERROR
;
1109 * @see FileBackendStore::directoryExists()
1111 * @param string $container Resolved container name
1112 * @param string $dir Resolved path relative to container
1113 * @param array $params
1116 abstract protected function doDirectoryExists( $container, $dir, array $params );
1118 final public function getDirectoryList( array $params ) {
1119 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
1120 if ( $dir === null ) {
1121 return self
::EXISTENCE_ERROR
; // invalid storage path
1123 if ( $shard !== null ) {
1124 // File listing is confined to a single container/shard
1125 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
1127 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
1128 // File listing spans multiple containers/shards
1129 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
1131 return new FileBackendStoreShardDirIterator( $this,
1132 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
1137 * Do not call this function from places outside FileBackend
1139 * @see FileBackendStore::getDirectoryList()
1141 * @param string $container Resolved container name
1142 * @param string $dir Resolved path relative to container
1143 * @param array $params
1144 * @return Traversable|array|null Iterable list or null (error)
1146 abstract public function getDirectoryListInternal( $container, $dir, array $params );
1148 final public function getFileList( array $params ) {
1149 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
1150 if ( $dir === null ) {
1151 return self
::LIST_ERROR
; // invalid storage path
1153 if ( $shard !== null ) {
1154 // File listing is confined to a single container/shard
1155 return $this->getFileListInternal( $fullCont, $dir, $params );
1157 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
1158 // File listing spans multiple containers/shards
1159 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
1161 return new FileBackendStoreShardFileIterator( $this,
1162 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
1167 * Do not call this function from places outside FileBackend
1169 * @see FileBackendStore::getFileList()
1171 * @param string $container Resolved container name
1172 * @param string $dir Resolved path relative to container
1173 * @param array $params
1174 * @return Traversable|string[]|null Iterable list or null (error)
1176 abstract public function getFileListInternal( $container, $dir, array $params );
1179 * Return a list of FileOp objects from a list of operations.
1180 * Do not call this function from places outside FileBackend.
1182 * The result must have the same number of items as the input.
1183 * An exception is thrown if an unsupported operation is requested.
1185 * @param array $ops Same format as doOperations()
1186 * @return FileOp[] List of FileOp objects
1187 * @throws FileBackendError
1189 final public function getOperationsInternal( array $ops ) {
1191 'store' => StoreFileOp
::class,
1192 'copy' => CopyFileOp
::class,
1193 'move' => MoveFileOp
::class,
1194 'delete' => DeleteFileOp
::class,
1195 'create' => CreateFileOp
::class,
1196 'describe' => DescribeFileOp
::class,
1197 'null' => NullFileOp
::class
1200 $performOps = []; // array of FileOp objects
1201 // Build up ordered array of FileOps...
1202 foreach ( $ops as $operation ) {
1203 $opName = $operation['op'];
1204 if ( isset( $supportedOps[$opName] ) ) {
1205 $class = $supportedOps[$opName];
1206 // Get params for this operation
1207 $params = $operation;
1208 // Append the FileOp class
1209 $performOps[] = new $class( $this, $params, $this->logger
);
1211 throw new FileBackendError( "Operation '$opName' is not supported." );
1219 * Get a list of storage paths to lock for a list of operations
1220 * Returns an array with LockManager::LOCK_UW (shared locks) and
1221 * LockManager::LOCK_EX (exclusive locks) keys, each corresponding
1222 * to a list of storage paths to be locked. All returned paths are
1225 * @param array $performOps List of FileOp objects
1226 * @return array (LockManager::LOCK_UW => path list, LockManager::LOCK_EX => path list)
1228 final public function getPathsToLockForOpsInternal( array $performOps ) {
1229 // Build up a list of files to lock...
1230 $paths = [ 'sh' => [], 'ex' => [] ];
1231 foreach ( $performOps as $fileOp ) {
1232 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1233 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1235 // Optimization: if doing an EX lock anyway, don't also set an SH one
1236 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1237 // Get a shared lock on the parent directory of each path changed
1238 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1241 LockManager
::LOCK_UW
=> $paths['sh'],
1242 LockManager
::LOCK_EX
=> $paths['ex']
1246 public function getScopedLocksForOps( array $ops, StatusValue
$status ) {
1247 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1249 return $this->getScopedFileLocks( $paths, 'mixed', $status );
1252 final protected function doOperationsInternal( array $ops, array $opts ) {
1253 /** @noinspection PhpUnusedLocalVariableInspection */
1254 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1255 $status = $this->newStatus();
1257 // Fix up custom header name/value pairs...
1258 $ops = array_map( [ $this, 'sanitizeOpHeaders' ], $ops );
1260 // Build up a list of FileOps...
1261 $performOps = $this->getOperationsInternal( $ops );
1263 // Acquire any locks as needed...
1264 if ( empty( $opts['nonLocking'] ) ) {
1265 // Build up a list of files to lock...
1266 $paths = $this->getPathsToLockForOpsInternal( $performOps );
1267 // Try to lock those files for the scope of this function...
1268 /** @noinspection PhpUnusedLocalVariableInspection */
1269 $scopeLock = $this->getScopedFileLocks( $paths, 'mixed', $status );
1270 if ( !$status->isOK() ) {
1271 return $status; // abort
1275 // Clear any file cache entries (after locks acquired)
1276 if ( empty( $opts['preserveCache'] ) ) {
1277 $this->clearCache();
1280 // Build the list of paths involved
1282 foreach ( $performOps as $performOp ) {
1283 $paths = array_merge( $paths, $performOp->storagePathsRead() );
1284 $paths = array_merge( $paths, $performOp->storagePathsChanged() );
1287 // Enlarge the cache to fit the stat entries of these files
1288 $this->cheapCache
->setMaxSize( max( 2 * count( $paths ), self
::CACHE_CHEAP_SIZE
) );
1290 // Load from the persistent container caches
1291 $this->primeContainerCache( $paths );
1292 // Get the latest stat info for all the files (having locked them)
1293 $ok = $this->preloadFileStat( [ 'srcs' => $paths, 'latest' => true ] );
1296 // Actually attempt the operation batch...
1297 $opts = $this->setConcurrencyFlags( $opts );
1298 $subStatus = FileOpBatch
::attempt( $performOps, $opts, $this->fileJournal
);
1300 // If we could not even stat some files, then bail out...
1301 $subStatus = $this->newStatus( 'backend-fail-internal', $this->name
);
1302 foreach ( $ops as $i => $op ) { // mark each op as failed
1303 $subStatus->success
[$i] = false;
1304 ++
$subStatus->failCount
;
1306 $this->logger
->error( static::class . "-{$this->name} " .
1307 " stat failure; aborted operations: " . FormatJson
::encode( $ops ) );
1310 // Merge errors into StatusValue fields
1311 $status->merge( $subStatus );
1312 $status->success
= $subStatus->success
; // not done in merge()
1314 // Shrink the stat cache back to normal size
1315 $this->cheapCache
->setMaxSize( self
::CACHE_CHEAP_SIZE
);
1320 final protected function doQuickOperationsInternal( array $ops ) {
1321 /** @noinspection PhpUnusedLocalVariableInspection */
1322 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1323 $status = $this->newStatus();
1325 // Fix up custom header name/value pairs...
1326 $ops = array_map( [ $this, 'sanitizeOpHeaders' ], $ops );
1328 // Clear any file cache entries
1329 $this->clearCache();
1331 $supportedOps = [ 'create', 'store', 'copy', 'move', 'delete', 'describe', 'null' ];
1332 // Parallel ops may be disabled in config due to dependencies (e.g. needing popen())
1333 $async = ( $this->parallelize
=== 'implicit' && count( $ops ) > 1 );
1334 $maxConcurrency = $this->concurrency
; // throttle
1335 /** @var StatusValue[] $statuses */
1336 $statuses = []; // array of (index => StatusValue)
1337 $fileOpHandles = []; // list of (index => handle) arrays
1338 $curFileOpHandles = []; // current handle batch
1339 // Perform the sync-only ops and build up op handles for the async ops...
1340 foreach ( $ops as $index => $params ) {
1341 if ( !in_array( $params['op'], $supportedOps ) ) {
1342 throw new FileBackendError( "Operation '{$params['op']}' is not supported." );
1344 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1345 $subStatus = $this->$method( [ 'async' => $async ] +
$params );
1346 if ( $subStatus->value
instanceof FileBackendStoreOpHandle
) { // async
1347 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1348 $fileOpHandles[] = $curFileOpHandles; // push this batch
1349 $curFileOpHandles = [];
1351 $curFileOpHandles[$index] = $subStatus->value
; // keep index
1352 } else { // error or completed
1353 $statuses[$index] = $subStatus; // keep index
1356 if ( count( $curFileOpHandles ) ) {
1357 $fileOpHandles[] = $curFileOpHandles; // last batch
1359 // Do all the async ops that can be done concurrently...
1360 foreach ( $fileOpHandles as $fileHandleBatch ) {
1361 $statuses = $statuses +
$this->executeOpHandlesInternal( $fileHandleBatch );
1363 // Marshall and merge all the responses...
1364 foreach ( $statuses as $index => $subStatus ) {
1365 $status->merge( $subStatus );
1366 if ( $subStatus->isOK() ) {
1367 $status->success
[$index] = true;
1368 ++
$status->successCount
;
1370 $status->success
[$index] = false;
1371 ++
$status->failCount
;
1379 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1380 * The resulting StatusValue object fields will correspond
1381 * to the order in which the handles where given.
1383 * @param FileBackendStoreOpHandle[] $fileOpHandles
1384 * @return StatusValue[] Map of StatusValue objects
1385 * @throws FileBackendError
1387 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1388 /** @noinspection PhpUnusedLocalVariableInspection */
1389 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1391 foreach ( $fileOpHandles as $fileOpHandle ) {
1392 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle
) ) {
1393 throw new InvalidArgumentException( "Expected FileBackendStoreOpHandle object." );
1394 } elseif ( $fileOpHandle->backend
->getName() !== $this->getName() ) {
1395 throw new InvalidArgumentException( "Expected handle for this file backend." );
1399 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1400 foreach ( $fileOpHandles as $fileOpHandle ) {
1401 $fileOpHandle->closeResources();
1408 * @see FileBackendStore::executeOpHandlesInternal()
1410 * @param FileBackendStoreOpHandle[] $fileOpHandles
1412 * @throws FileBackendError
1413 * @return StatusValue[] List of corresponding StatusValue objects
1415 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1416 if ( count( $fileOpHandles ) ) {
1417 throw new FileBackendError( "Backend does not support asynchronous operations." );
1424 * Normalize and filter HTTP headers from a file operation
1426 * This normalizes and strips long HTTP headers from a file operation.
1427 * Most headers are just numbers, but some are allowed to be long.
1428 * This function is useful for cleaning up headers and avoiding backend
1429 * specific errors, especially in the middle of batch file operations.
1431 * @param array $op Same format as doOperation()
1434 protected function sanitizeOpHeaders( array $op ) {
1435 static $longs = [ 'content-disposition' ];
1437 if ( isset( $op['headers'] ) ) { // op sets HTTP headers
1439 foreach ( $op['headers'] as $name => $value ) {
1440 $name = strtolower( $name );
1441 $maxHVLen = in_array( $name, $longs ) ? INF
: 255;
1442 if ( strlen( $name ) > 255 ||
strlen( $value ) > $maxHVLen ) {
1443 trigger_error( "Header '$name: $value' is too long." );
1445 $newHeaders[$name] = strlen( $value ) ?
$value : ''; // null/false => ""
1448 $op['headers'] = $newHeaders;
1454 final public function preloadCache( array $paths ) {
1455 $fullConts = []; // full container names
1456 foreach ( $paths as $path ) {
1457 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1458 $fullConts[] = $fullCont;
1460 // Load from the persistent file and container caches
1461 $this->primeContainerCache( $fullConts );
1462 $this->primeFileCache( $paths );
1465 final public function clearCache( array $paths = null ) {
1466 if ( is_array( $paths ) ) {
1467 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1468 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1470 if ( $paths === null ) {
1471 $this->cheapCache
->clear();
1472 $this->expensiveCache
->clear();
1474 foreach ( $paths as $path ) {
1475 $this->cheapCache
->clear( $path );
1476 $this->expensiveCache
->clear( $path );
1479 $this->doClearCache( $paths );
1483 * Clears any additional stat caches for storage paths
1485 * @see FileBackend::clearCache()
1487 * @param array|null $paths Storage paths (optional)
1489 protected function doClearCache( array $paths = null ) {
1492 final public function preloadFileStat( array $params ) {
1493 /** @noinspection PhpUnusedLocalVariableInspection */
1494 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1496 $params['concurrency'] = ( $this->parallelize
!== 'off' ) ?
$this->concurrency
: 1;
1497 $stats = $this->doGetFileStatMulti( $params );
1498 if ( $stats === null ) {
1499 return true; // not supported
1502 // Whether this queried the backend in high consistency mode
1503 $latest = !empty( $params['latest'] );
1505 return $this->ingestFreshFileStats( $stats, $latest );
1509 * Get file stat information (concurrently if possible) for several files
1511 * @see FileBackend::getFileStat()
1513 * @param array $params Parameters include:
1514 * - srcs : list of source storage paths
1515 * - latest : use the latest available data
1516 * @return array|null Map of storage paths to array|bool|null (returns null if not supported)
1519 protected function doGetFileStatMulti( array $params ) {
1520 return null; // not supported
1524 * Is this a key/value store where directories are just virtual?
1525 * Virtual directories exists in so much as files exists that are
1526 * prefixed with the directory path followed by a forward slash.
1530 abstract protected function directoriesAreVirtual();
1533 * Check if a short container name is valid
1535 * This checks for length and illegal characters.
1536 * This may disallow certain characters that can appear
1537 * in the prefix used to make the full container name.
1539 * @param string $container
1542 final protected static function isValidShortContainerName( $container ) {
1543 // Suffixes like '.xxx' (hex shard chars) or '.seg' (file segments)
1544 // might be used by subclasses. Reserve the dot character for sanity.
1545 // The only way dots end up in containers (e.g. resolveStoragePath)
1546 // is due to the wikiId container prefix or the above suffixes.
1547 return self
::isValidContainerName( $container ) && !preg_match( '/[.]/', $container );
1551 * Check if a full container name is valid
1553 * This checks for length and illegal characters.
1554 * Limiting the characters makes migrations to other stores easier.
1556 * @param string $container
1559 final protected static function isValidContainerName( $container ) {
1560 // This accounts for NTFS, Swift, and Ceph restrictions
1561 // and disallows directory separators or traversal characters.
1562 // Note that matching strings URL encode to the same string;
1563 // in Swift/Ceph, the length restriction is *after* URL encoding.
1564 return (bool)preg_match( '/^[a-z0-9][a-z0-9-_.]{0,199}$/i', $container );
1568 * Splits a storage path into an internal container name,
1569 * an internal relative file name, and a container shard suffix.
1570 * Any shard suffix is already appended to the internal container name.
1571 * This also checks that the storage path is valid and within this backend.
1573 * If the container is sharded but a suffix could not be determined,
1574 * this means that the path can only refer to a directory and can only
1575 * be scanned by looking in all the container shards.
1577 * @param string $storagePath
1578 * @return array (container, path, container suffix) or (null, null, null) if invalid
1580 final protected function resolveStoragePath( $storagePath ) {
1581 list( $backend, $shortCont, $relPath ) = self
::splitStoragePath( $storagePath );
1582 if ( $backend === $this->name
) { // must be for this backend
1583 $relPath = self
::normalizeContainerPath( $relPath );
1584 if ( $relPath !== null && self
::isValidShortContainerName( $shortCont ) ) {
1585 // Get shard for the normalized path if this container is sharded
1586 $cShard = $this->getContainerShard( $shortCont, $relPath );
1587 // Validate and sanitize the relative path (backend-specific)
1588 $relPath = $this->resolveContainerPath( $shortCont, $relPath );
1589 if ( $relPath !== null ) {
1590 // Prepend any wiki ID prefix to the container name
1591 $container = $this->fullContainerName( $shortCont );
1592 if ( self
::isValidContainerName( $container ) ) {
1593 // Validate and sanitize the container name (backend-specific)
1594 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1595 if ( $container !== null ) {
1596 return [ $container, $relPath, $cShard ];
1603 return [ null, null, null ];
1607 * Like resolveStoragePath() except null values are returned if
1608 * the container is sharded and the shard could not be determined
1609 * or if the path ends with '/'. The latter case is illegal for FS
1610 * backends and can confuse listings for object store backends.
1612 * This function is used when resolving paths that must be valid
1613 * locations for files. Directory and listing functions should
1614 * generally just use resolveStoragePath() instead.
1616 * @see FileBackendStore::resolveStoragePath()
1618 * @param string $storagePath
1619 * @return array (container, path) or (null, null) if invalid
1621 final protected function resolveStoragePathReal( $storagePath ) {
1622 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1623 if ( $cShard !== null && substr( $relPath, -1 ) !== '/' ) {
1624 return [ $container, $relPath ];
1627 return [ null, null ];
1631 * Get the container name shard suffix for a given path.
1632 * Any empty suffix means the container is not sharded.
1634 * @param string $container Container name
1635 * @param string $relPath Storage path relative to the container
1636 * @return string|null Returns null if shard could not be determined
1638 final protected function getContainerShard( $container, $relPath ) {
1639 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1640 if ( $levels == 1 ||
$levels == 2 ) {
1641 // Hash characters are either base 16 or 36
1642 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1643 // Get a regex that represents the shard portion of paths.
1644 // The concatenation of the captures gives us the shard.
1645 if ( $levels === 1 ) { // 16 or 36 shards per container
1646 $hashDirRegex = '(' . $char . ')';
1647 } else { // 256 or 1296 shards per container
1648 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1649 $hashDirRegex = $char . '/(' . $char . '{2})';
1650 } else { // short hash dir format (e.g. "a/b/c")
1651 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1654 // Allow certain directories to be above the hash dirs so as
1655 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1656 // They must be 2+ chars to avoid any hash directory ambiguity.
1658 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1659 return '.' . implode( '', array_slice( $m, 1 ) );
1662 return null; // failed to match
1665 return ''; // no sharding
1669 * Check if a storage path maps to a single shard.
1670 * Container dirs like "a", where the container shards on "x/xy",
1671 * can reside on several shards. Such paths are tricky to handle.
1673 * @param string $storagePath Storage path
1676 final public function isSingleShardPathInternal( $storagePath ) {
1677 list( , , $shard ) = $this->resolveStoragePath( $storagePath );
1679 return ( $shard !== null );
1683 * Get the sharding config for a container.
1684 * If greater than 0, then all file storage paths within
1685 * the container are required to be hashed accordingly.
1687 * @param string $container
1688 * @return array (integer levels, integer base, repeat flag) or (0, 0, false)
1690 final protected function getContainerHashLevels( $container ) {
1691 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1692 $config = $this->shardViaHashLevels
[$container];
1693 $hashLevels = (int)$config['levels'];
1694 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1695 $hashBase = (int)$config['base'];
1696 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1697 return [ $hashLevels, $hashBase, $config['repeat'] ];
1702 return [ 0, 0, false ]; // no sharding
1706 * Get a list of full container shard suffixes for a container
1708 * @param string $container
1711 final protected function getContainerSuffixes( $container ) {
1713 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1714 if ( $digits > 0 ) {
1715 $numShards = $base ** $digits;
1716 for ( $index = 0; $index < $numShards; $index++
) {
1717 $shards[] = '.' . Wikimedia\base_convert
( $index, 10, $base, $digits );
1725 * Get the full container name, including the wiki ID prefix
1727 * @param string $container
1730 final protected function fullContainerName( $container ) {
1731 if ( $this->domainId
!= '' ) {
1732 return "{$this->domainId}-$container";
1739 * Resolve a container name, checking if it's allowed by the backend.
1740 * This is intended for internal use, such as encoding illegal chars.
1741 * Subclasses can override this to be more restrictive.
1743 * @param string $container
1744 * @return string|null
1746 protected function resolveContainerName( $container ) {
1751 * Resolve a relative storage path, checking if it's allowed by the backend.
1752 * This is intended for internal use, such as encoding illegal chars or perhaps
1753 * getting absolute paths (e.g. FS based backends). Note that the relative path
1754 * may be the empty string (e.g. the path is simply to the container).
1756 * @param string $container Container name
1757 * @param string $relStoragePath Storage path relative to the container
1758 * @return string|null Path or null if not valid
1760 protected function resolveContainerPath( $container, $relStoragePath ) {
1761 return $relStoragePath;
1765 * Get the cache key for a container
1767 * @param string $container Resolved container name
1770 private function containerCacheKey( $container ) {
1771 return "filebackend:{$this->name}:{$this->domainId}:container:{$container}";
1775 * Set the cached info for a container
1777 * @param string $container Resolved container name
1778 * @param array $val Information to cache
1780 final protected function setContainerCache( $container, array $val ) {
1781 $this->memCache
->set( $this->containerCacheKey( $container ), $val, 14 * 86400 );
1785 * Delete the cached info for a container.
1786 * The cache key is salted for a while to prevent race conditions.
1788 * @param string $container Resolved container name
1790 final protected function deleteContainerCache( $container ) {
1791 if ( !$this->memCache
->delete( $this->containerCacheKey( $container ), 300 ) ) {
1792 trigger_error( "Unable to delete stat cache for container $container." );
1797 * Do a batch lookup from cache for container stats for all containers
1798 * used in a list of container names or storage paths objects.
1799 * This loads the persistent cache values into the process cache.
1801 * @param array $items
1803 final protected function primeContainerCache( array $items ) {
1804 /** @noinspection PhpUnusedLocalVariableInspection */
1805 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1807 $paths = []; // list of storage paths
1808 $contNames = []; // (cache key => resolved container name)
1809 // Get all the paths/containers from the items...
1810 foreach ( $items as $item ) {
1811 if ( self
::isStoragePath( $item ) ) {
1813 } elseif ( is_string( $item ) ) { // full container name
1814 $contNames[$this->containerCacheKey( $item )] = $item;
1817 // Get all the corresponding cache keys for paths...
1818 foreach ( $paths as $path ) {
1819 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1820 if ( $fullCont !== null ) { // valid path for this backend
1821 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1825 $contInfo = []; // (resolved container name => cache value)
1826 // Get all cache entries for these container cache keys...
1827 $values = $this->memCache
->getMulti( array_keys( $contNames ) );
1828 foreach ( $values as $cacheKey => $val ) {
1829 $contInfo[$contNames[$cacheKey]] = $val;
1832 // Populate the container process cache for the backend...
1833 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1837 * Fill the backend-specific process cache given an array of
1838 * resolved container names and their corresponding cached info.
1839 * Only containers that actually exist should appear in the map.
1841 * @param array $containerInfo Map of resolved container names to cached info
1843 protected function doPrimeContainerCache( array $containerInfo ) {
1847 * Get the cache key for a file path
1849 * @param string $path Normalized storage path
1852 private function fileCacheKey( $path ) {
1853 return "filebackend:{$this->name}:{$this->domainId}:file:" . sha1( $path );
1857 * Set the cached stat info for a file path.
1858 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1859 * salting for the case when a file is created at a path were there was none before.
1861 * @param string $path Storage path
1862 * @param array $val Stat information to cache
1864 final protected function setFileCache( $path, array $val ) {
1865 $path = FileBackend
::normalizeStoragePath( $path );
1866 if ( $path === null ) {
1867 return; // invalid storage path
1869 $mtime = ConvertibleTimestamp
::convert( TS_UNIX
, $val['mtime'] );
1870 $ttl = $this->memCache
->adaptiveTTL( $mtime, 7 * 86400, 300, 0.1 );
1871 $key = $this->fileCacheKey( $path );
1872 // Set the cache unless it is currently salted.
1873 $this->memCache
->set( $key, $val, $ttl );
1877 * Delete the cached stat info for a file path.
1878 * The cache key is salted for a while to prevent race conditions.
1879 * Since negatives (404s) are not cached, this does not need to be called when
1880 * a file is created at a path were there was none before.
1882 * @param string $path Storage path
1884 final protected function deleteFileCache( $path ) {
1885 $path = FileBackend
::normalizeStoragePath( $path );
1886 if ( $path === null ) {
1887 return; // invalid storage path
1889 if ( !$this->memCache
->delete( $this->fileCacheKey( $path ), 300 ) ) {
1890 trigger_error( "Unable to delete stat cache for file $path." );
1895 * Do a batch lookup from cache for file stats for all paths
1896 * used in a list of storage paths or FileOp objects.
1897 * This loads the persistent cache values into the process cache.
1899 * @param array $items List of storage paths
1901 final protected function primeFileCache( array $items ) {
1902 /** @noinspection PhpUnusedLocalVariableInspection */
1903 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1905 $paths = []; // list of storage paths
1906 $pathNames = []; // (cache key => storage path)
1907 // Get all the paths/containers from the items...
1908 foreach ( $items as $item ) {
1909 if ( self
::isStoragePath( $item ) ) {
1910 $paths[] = FileBackend
::normalizeStoragePath( $item );
1913 // Get rid of any paths that failed normalization
1914 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1915 // Get all the corresponding cache keys for paths...
1916 foreach ( $paths as $path ) {
1917 list( , $rel, ) = $this->resolveStoragePath( $path );
1918 if ( $rel !== null ) { // valid path for this backend
1919 $pathNames[$this->fileCacheKey( $path )] = $path;
1922 // Get all cache entries for these file cache keys.
1923 // Note that negatives are not cached by getFileStat()/preloadFileStat().
1924 $values = $this->memCache
->getMulti( array_keys( $pathNames ) );
1925 // Load all of the results into process cache...
1926 foreach ( array_filter( $values, 'is_array' ) as $cacheKey => $stat ) {
1927 $path = $pathNames[$cacheKey];
1928 // Sanity; this flag only applies to stat info loaded directly
1929 // from a high consistency backend query to the process cache
1930 unset( $stat['latest'] );
1932 $this->cheapCache
->setField( $path, 'stat', $stat );
1933 if ( isset( $stat['sha1'] ) && strlen( $stat['sha1'] ) == 31 ) {
1934 // Some backends store SHA-1 as metadata
1935 $this->cheapCache
->setField(
1938 [ 'hash' => $stat['sha1'], 'latest' => false ]
1941 if ( isset( $stat['xattr'] ) && is_array( $stat['xattr'] ) ) {
1942 // Some backends store custom headers/metadata
1943 $stat['xattr'] = self
::normalizeXAttributes( $stat['xattr'] );
1944 $this->cheapCache
->setField(
1947 [ 'map' => $stat['xattr'], 'latest' => false ]
1954 * Normalize file headers/metadata to the FileBackend::getFileXAttributes() format
1956 * @param array $xattr
1960 final protected static function normalizeXAttributes( array $xattr ) {
1961 $newXAttr = [ 'headers' => [], 'metadata' => [] ];
1963 foreach ( $xattr['headers'] as $name => $value ) {
1964 $newXAttr['headers'][strtolower( $name )] = $value;
1967 foreach ( $xattr['metadata'] as $name => $value ) {
1968 $newXAttr['metadata'][strtolower( $name )] = $value;
1975 * Set the 'concurrency' option from a list of operation options
1977 * @param array $opts Map of operation options
1980 final protected function setConcurrencyFlags( array $opts ) {
1981 $opts['concurrency'] = 1; // off
1982 if ( $this->parallelize
=== 'implicit' ) {
1983 if ( !isset( $opts['parallelize'] ) ||
$opts['parallelize'] ) {
1984 $opts['concurrency'] = $this->concurrency
;
1986 } elseif ( $this->parallelize
=== 'explicit' ) {
1987 if ( !empty( $opts['parallelize'] ) ) {
1988 $opts['concurrency'] = $this->concurrency
;
1996 * Get the content type to use in HEAD/GET requests for a file
1998 * @param string $storagePath
1999 * @param string|null $content File data
2000 * @param string|null $fsPath File system path
2001 * @return string MIME type
2003 protected function getContentType( $storagePath, $content, $fsPath ) {
2004 if ( $this->mimeCallback
) {
2005 return call_user_func_array( $this->mimeCallback
, func_get_args() );
2008 $mime = ( $fsPath !== null ) ?
mime_content_type( $fsPath ) : false;
2009 return $mime ?
: 'unknown/unknown';