3 * Base class for all backends using particular storage medium.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup FileBackend
23 use Wikimedia\AtEase\AtEase
;
24 use Wikimedia\Timestamp\ConvertibleTimestamp
;
27 * @brief Base class for all backends using particular storage medium.
29 * This class defines the methods as abstract that subclasses must implement.
30 * Outside callers should *not* use functions with "Internal" in the name.
32 * The FileBackend operations are implemented using basic functions
33 * such as storeInternal(), copyInternal(), deleteInternal() and the like.
34 * This class is also responsible for path resolution and sanitization.
36 * @ingroup FileBackend
39 abstract class FileBackendStore
extends FileBackend
{
40 /** @var WANObjectCache */
44 /** @var MapCacheLRU Map of paths to small (RAM/disk) cache items */
45 protected $cheapCache;
46 /** @var MapCacheLRU Map of paths to large (RAM/disk) cache items */
47 protected $expensiveCache;
49 /** @var array Map of container names to sharding config */
50 protected $shardViaHashLevels = [];
52 /** @var callable Method to get the MIME type of files */
53 protected $mimeCallback;
55 protected $maxFileSize = 4294967296; // integer bytes (4GiB)
57 const CACHE_TTL
= 10; // integer; TTL in seconds for process cache entries
58 const CACHE_CHEAP_SIZE
= 500; // integer; max entries in "cheap cache"
59 const CACHE_EXPENSIVE_SIZE
= 5; // integer; max entries in "expensive cache"
62 * @see FileBackend::__construct()
63 * Additional $config params include:
64 * - srvCache : BagOStuff cache to APC or the like.
65 * - wanCache : WANObjectCache object to use for persistent caching.
66 * - mimeCallback : Callback that takes (storage path, content, file system path) and
67 * returns the MIME type of the file or 'unknown/unknown'. The file
68 * system path parameter should be used if the content one is null.
70 * @param array $config
72 public function __construct( array $config ) {
73 parent
::__construct( $config );
74 $this->mimeCallback
= $config['mimeCallback'] ??
null;
75 $this->srvCache
= new EmptyBagOStuff(); // disabled by default
76 $this->memCache
= WANObjectCache
::newEmpty(); // disabled by default
77 $this->cheapCache
= new MapCacheLRU( self
::CACHE_CHEAP_SIZE
);
78 $this->expensiveCache
= new MapCacheLRU( self
::CACHE_EXPENSIVE_SIZE
);
82 * Get the maximum allowable file size given backend
83 * medium restrictions and basic performance constraints.
84 * Do not call this function from places outside FileBackend and FileOp.
88 final public function maxFileSizeInternal() {
89 return $this->maxFileSize
;
93 * Check if a file can be created or changed at a given storage path.
94 * FS backends should check if the parent directory exists, files can be
95 * written under it, and that any file already there is writable.
96 * Backends using key/value stores should check if the container exists.
98 * @param string $storagePath
101 abstract public function isPathUsableInternal( $storagePath );
104 * Create a file in the backend with the given contents.
105 * This will overwrite any file that exists at the destination.
106 * Do not call this function from places outside FileBackend and FileOp.
109 * - content : the raw file contents
110 * - dst : destination storage path
111 * - headers : HTTP header name/value map
112 * - async : StatusValue will be returned immediately if supported.
113 * If the StatusValue is OK, then its value field will be
114 * set to a FileBackendStoreOpHandle object.
115 * - dstExists : Whether a file exists at the destination (optimization).
116 * Callers can use "false" if no existing file is being changed.
118 * @param array $params
119 * @return StatusValue
121 final public function createInternal( array $params ) {
122 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
123 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
124 $status = $this->newStatus( 'backend-fail-maxsize',
125 $params['dst'], $this->maxFileSizeInternal() );
127 $status = $this->doCreateInternal( $params );
128 $this->clearCache( [ $params['dst'] ] );
129 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
130 $this->deleteFileCache( $params['dst'] ); // persistent cache
138 * @see FileBackendStore::createInternal()
139 * @param array $params
140 * @return StatusValue
142 abstract protected function doCreateInternal( array $params );
145 * Store a file into the backend from a file on disk.
146 * This will overwrite any file that exists at the destination.
147 * Do not call this function from places outside FileBackend and FileOp.
150 * - src : source path on disk
151 * - dst : destination storage path
152 * - headers : HTTP header name/value map
153 * - async : StatusValue will be returned immediately if supported.
154 * If the StatusValue is OK, then its value field will be
155 * set to a FileBackendStoreOpHandle object.
156 * - dstExists : Whether a file exists at the destination (optimization).
157 * Callers can use "false" if no existing file is being changed.
159 * @param array $params
160 * @return StatusValue
162 final public function storeInternal( array $params ) {
163 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
164 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
165 $status = $this->newStatus( 'backend-fail-maxsize',
166 $params['dst'], $this->maxFileSizeInternal() );
168 $status = $this->doStoreInternal( $params );
169 $this->clearCache( [ $params['dst'] ] );
170 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
171 $this->deleteFileCache( $params['dst'] ); // persistent cache
179 * @see FileBackendStore::storeInternal()
180 * @param array $params
181 * @return StatusValue
183 abstract protected function doStoreInternal( array $params );
186 * Copy a file from one storage path to another in the backend.
187 * This will overwrite any file that exists at the destination.
188 * Do not call this function from places outside FileBackend and FileOp.
191 * - src : source storage path
192 * - dst : destination storage path
193 * - ignoreMissingSource : do nothing if the source file does not exist
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 copyInternal( array $params ) {
205 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
206 $status = $this->doCopyInternal( $params );
207 $this->clearCache( [ $params['dst'] ] );
208 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
209 $this->deleteFileCache( $params['dst'] ); // persistent cache
216 * @see FileBackendStore::copyInternal()
217 * @param array $params
218 * @return StatusValue
220 abstract protected function doCopyInternal( array $params );
223 * Delete a file at the storage path.
224 * Do not call this function from places outside FileBackend and FileOp.
227 * - src : source storage path
228 * - ignoreMissingSource : do nothing if the source file does not exist
229 * - async : StatusValue will be returned immediately if supported.
230 * If the StatusValue is OK, then its value field will be
231 * set to a FileBackendStoreOpHandle object.
233 * @param array $params
234 * @return StatusValue
236 final public function deleteInternal( array $params ) {
237 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
238 $status = $this->doDeleteInternal( $params );
239 $this->clearCache( [ $params['src'] ] );
240 $this->deleteFileCache( $params['src'] ); // persistent cache
245 * @see FileBackendStore::deleteInternal()
246 * @param array $params
247 * @return StatusValue
249 abstract protected function doDeleteInternal( array $params );
252 * Move a file from one storage path to another in the backend.
253 * This will overwrite any file that exists at the destination.
254 * Do not call this function from places outside FileBackend and FileOp.
257 * - src : source storage path
258 * - dst : destination storage path
259 * - ignoreMissingSource : do nothing if the source file does not exist
260 * - headers : HTTP header name/value map
261 * - async : StatusValue will be returned immediately if supported.
262 * If the StatusValue is OK, then its value field will be
263 * set to a FileBackendStoreOpHandle object.
264 * - dstExists : Whether a file exists at the destination (optimization).
265 * Callers can use "false" if no existing file is being changed.
267 * @param array $params
268 * @return StatusValue
270 final public function moveInternal( array $params ) {
271 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
272 $status = $this->doMoveInternal( $params );
273 $this->clearCache( [ $params['src'], $params['dst'] ] );
274 $this->deleteFileCache( $params['src'] ); // persistent cache
275 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
276 $this->deleteFileCache( $params['dst'] ); // persistent cache
283 * @see FileBackendStore::moveInternal()
284 * @param array $params
285 * @return StatusValue
287 protected function doMoveInternal( array $params ) {
288 unset( $params['async'] ); // two steps, won't work here :)
289 $nsrc = FileBackend
::normalizeStoragePath( $params['src'] );
290 $ndst = FileBackend
::normalizeStoragePath( $params['dst'] );
291 // Copy source to dest
292 $status = $this->copyInternal( $params );
293 if ( $nsrc !== $ndst && $status->isOK() ) {
294 // Delete source (only fails due to races or network problems)
295 $status->merge( $this->deleteInternal( [ 'src' => $params['src'] ] ) );
296 $status->setResult( true, $status->value
); // ignore delete() errors
303 * Alter metadata for a file at the storage path.
304 * Do not call this function from places outside FileBackend and FileOp.
307 * - src : source storage path
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.
313 * @param array $params
314 * @return StatusValue
316 final public function describeInternal( array $params ) {
317 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
318 if ( count( $params['headers'] ) ) {
319 $status = $this->doDescribeInternal( $params );
320 $this->clearCache( [ $params['src'] ] );
321 $this->deleteFileCache( $params['src'] ); // persistent cache
323 $status = $this->newStatus(); // nothing to do
330 * @see FileBackendStore::describeInternal()
331 * @param array $params
332 * @return StatusValue
334 protected function doDescribeInternal( array $params ) {
335 return $this->newStatus();
339 * No-op file operation that does nothing.
340 * Do not call this function from places outside FileBackend and FileOp.
342 * @param array $params
343 * @return StatusValue
345 final public function nullInternal( array $params ) {
346 return $this->newStatus();
349 final public function concatenate( array $params ) {
350 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
351 $status = $this->newStatus();
353 // Try to lock the source files for the scope of this function
354 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager
::LOCK_UW
, $status );
355 if ( $status->isOK() ) {
356 // Actually do the file concatenation...
357 $start_time = microtime( true );
358 $status->merge( $this->doConcatenate( $params ) );
359 $sec = microtime( true ) - $start_time;
360 if ( !$status->isOK() ) {
361 $this->logger
->error( static::class . "-{$this->name}" .
362 " failed to concatenate " . count( $params['srcs'] ) . " file(s) [$sec sec]" );
370 * @see FileBackendStore::concatenate()
371 * @param array $params
372 * @return StatusValue
374 protected function doConcatenate( array $params ) {
375 $status = $this->newStatus();
376 $tmpPath = $params['dst']; // convenience
377 unset( $params['latest'] ); // sanity
379 // Check that the specified temp file is valid...
380 AtEase
::suppressWarnings();
381 $ok = ( is_file( $tmpPath ) && filesize( $tmpPath ) == 0 );
382 AtEase
::restoreWarnings();
383 if ( !$ok ) { // not present or not empty
384 $status->fatal( 'backend-fail-opentemp', $tmpPath );
389 // Get local FS versions of the chunks needed for the concatenation...
390 $fsFiles = $this->getLocalReferenceMulti( $params );
391 foreach ( $fsFiles as $path => &$fsFile ) {
392 if ( !$fsFile ) { // chunk failed to download?
393 $fsFile = $this->getLocalReference( [ 'src' => $path ] );
394 if ( !$fsFile ) { // retry failed?
395 $status->fatal( 'backend-fail-read', $path );
401 unset( $fsFile ); // unset reference so we can reuse $fsFile
403 // Get a handle for the destination temp file
404 $tmpHandle = fopen( $tmpPath, 'ab' );
405 if ( $tmpHandle === false ) {
406 $status->fatal( 'backend-fail-opentemp', $tmpPath );
411 // Build up the temp file using the source chunks (in order)...
412 foreach ( $fsFiles as $virtualSource => $fsFile ) {
413 // Get a handle to the local FS version
414 $sourceHandle = fopen( $fsFile->getPath(), 'rb' );
415 if ( $sourceHandle === false ) {
416 fclose( $tmpHandle );
417 $status->fatal( 'backend-fail-read', $virtualSource );
421 // Append chunk to file (pass chunk size to avoid magic quotes)
422 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
423 fclose( $sourceHandle );
424 fclose( $tmpHandle );
425 $status->fatal( 'backend-fail-writetemp', $tmpPath );
429 fclose( $sourceHandle );
431 if ( !fclose( $tmpHandle ) ) {
432 $status->fatal( 'backend-fail-closetemp', $tmpPath );
437 clearstatcache(); // temp file changed
442 final protected function doPrepare( array $params ) {
443 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
444 $status = $this->newStatus();
446 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
447 if ( $dir === null ) {
448 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
450 return $status; // invalid storage path
453 if ( $shard !== null ) { // confined to a single container/shard
454 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
455 } else { // directory is on several shards
456 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
457 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
458 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
459 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
467 * @see FileBackendStore::doPrepare()
468 * @param string $container
470 * @param array $params
471 * @return StatusValue
473 protected function doPrepareInternal( $container, $dir, array $params ) {
474 return $this->newStatus();
477 final protected function doSecure( array $params ) {
478 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
479 $status = $this->newStatus();
481 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
482 if ( $dir === null ) {
483 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
485 return $status; // invalid storage path
488 if ( $shard !== null ) { // confined to a single container/shard
489 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
490 } else { // directory is on several shards
491 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
492 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
493 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
494 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
502 * @see FileBackendStore::doSecure()
503 * @param string $container
505 * @param array $params
506 * @return StatusValue
508 protected function doSecureInternal( $container, $dir, array $params ) {
509 return $this->newStatus();
512 final protected function doPublish( array $params ) {
513 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
514 $status = $this->newStatus();
516 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
517 if ( $dir === null ) {
518 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
520 return $status; // invalid storage path
523 if ( $shard !== null ) { // confined to a single container/shard
524 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
525 } else { // directory is on several shards
526 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
527 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
528 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
529 $status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
537 * @see FileBackendStore::doPublish()
538 * @param string $container
540 * @param array $params
541 * @return StatusValue
543 protected function doPublishInternal( $container, $dir, array $params ) {
544 return $this->newStatus();
547 final protected function doClean( array $params ) {
548 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
549 $status = $this->newStatus();
551 // Recursive: first delete all empty subdirs recursively
552 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
553 $subDirsRel = $this->getTopDirectoryList( [ 'dir' => $params['dir'] ] );
554 if ( $subDirsRel !== null ) { // no errors
555 foreach ( $subDirsRel as $subDirRel ) {
556 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
557 $status->merge( $this->doClean( [ 'dir' => $subDir ] +
$params ) );
559 unset( $subDirsRel ); // free directory for rmdir() on Windows (for FS backends)
563 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
564 if ( $dir === null ) {
565 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
567 return $status; // invalid storage path
570 // Attempt to lock this directory...
571 $filesLockEx = [ $params['dir'] ];
572 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
573 if ( !$status->isOK() ) {
574 return $status; // abort
577 if ( $shard !== null ) { // confined to a single container/shard
578 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
579 $this->deleteContainerCache( $fullCont ); // purge cache
580 } else { // directory is on several shards
581 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
582 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
583 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
584 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
585 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
593 * @see FileBackendStore::doClean()
594 * @param string $container
596 * @param array $params
597 * @return StatusValue
599 protected function doCleanInternal( $container, $dir, array $params ) {
600 return $this->newStatus();
603 final public function fileExists( array $params ) {
604 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
605 $stat = $this->getFileStat( $params );
607 return ( $stat === null ) ?
null : (bool)$stat; // null => failure
610 final public function getFileTimestamp( array $params ) {
611 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
612 $stat = $this->getFileStat( $params );
614 return $stat ?
$stat['mtime'] : false;
617 final public function getFileSize( array $params ) {
618 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
619 $stat = $this->getFileStat( $params );
621 return $stat ?
$stat['size'] : false;
624 final public function getFileStat( array $params ) {
625 $path = self
::normalizeStoragePath( $params['src'] );
626 if ( $path === null ) {
627 return false; // invalid storage path
629 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
631 $latest = !empty( $params['latest'] ); // use latest data?
632 $requireSHA1 = !empty( $params['requireSHA1'] ); // require SHA-1 if file exists?
635 $stat = $this->cheapCache
->getField( $path, 'stat', self
::CACHE_TTL
);
636 // Note that some backends, like SwiftFileBackend, sometimes set file stat process
637 // cache entries from mass object listings that do not include the SHA-1. In that
638 // case, loading the persistent stat cache will likely yield the SHA-1.
641 ( $requireSHA1 && is_array( $stat ) && !isset( $stat['sha1'] ) )
643 $this->primeFileCache( [ $path ] ); // check persistent cache
647 $stat = $this->cheapCache
->getField( $path, 'stat', self
::CACHE_TTL
);
648 // If we want the latest data, check that this cached
649 // value was in fact fetched with the latest available data.
650 if ( is_array( $stat ) ) {
652 ( !$latest ||
$stat['latest'] ) &&
653 ( !$requireSHA1 ||
isset( $stat['sha1'] ) )
657 } elseif ( in_array( $stat, [ 'NOT_EXIST', 'NOT_EXIST_LATEST' ], true ) ) {
658 if ( !$latest ||
$stat === 'NOT_EXIST_LATEST' ) {
663 $stat = $this->doGetFileStat( $params );
665 if ( is_array( $stat ) ) { // file exists
666 // Strongly consistent backends can automatically set "latest"
667 $stat['latest'] = $stat['latest'] ??
$latest;
668 $this->cheapCache
->setField( $path, 'stat', $stat );
669 $this->setFileCache( $path, $stat ); // update persistent cache
670 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
671 $this->cheapCache
->setField( $path, 'sha1',
672 [ 'hash' => $stat['sha1'], 'latest' => $latest ] );
674 if ( isset( $stat['xattr'] ) ) { // some backends store headers/metadata
675 $stat['xattr'] = self
::normalizeXAttributes( $stat['xattr'] );
676 $this->cheapCache
->setField( $path, 'xattr',
677 [ 'map' => $stat['xattr'], 'latest' => $latest ] );
679 } elseif ( $stat === false ) { // file does not exist
680 $this->cheapCache
->setField( $path, 'stat', $latest ?
'NOT_EXIST_LATEST' : 'NOT_EXIST' );
681 $this->cheapCache
->setField( $path, 'xattr', [ 'map' => false, 'latest' => $latest ] );
682 $this->cheapCache
->setField( $path, 'sha1', [ 'hash' => false, 'latest' => $latest ] );
683 $this->logger
->debug( __METHOD__
. ': File {path} does not exist', [
686 } else { // an error occurred
687 $this->logger
->warning( __METHOD__
. ': Could not stat file {path}', [
696 * @see FileBackendStore::getFileStat()
697 * @param array $params
699 abstract protected function doGetFileStat( array $params );
701 public function getFileContentsMulti( array $params ) {
702 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
704 $params = $this->setConcurrencyFlags( $params );
705 $contents = $this->doGetFileContentsMulti( $params );
711 * @see FileBackendStore::getFileContentsMulti()
712 * @param array $params
715 protected function doGetFileContentsMulti( array $params ) {
717 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
718 AtEase
::suppressWarnings();
719 $contents[$path] = $fsFile ?
file_get_contents( $fsFile->getPath() ) : false;
720 AtEase
::restoreWarnings();
726 final public function getFileXAttributes( array $params ) {
727 $path = self
::normalizeStoragePath( $params['src'] );
728 if ( $path === null ) {
729 return false; // invalid storage path
731 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
732 $latest = !empty( $params['latest'] ); // use latest data?
733 if ( $this->cheapCache
->hasField( $path, 'xattr', self
::CACHE_TTL
) ) {
734 $stat = $this->cheapCache
->getField( $path, 'xattr' );
735 // If we want the latest data, check that this cached
736 // value was in fact fetched with the latest available data.
737 if ( !$latest ||
$stat['latest'] ) {
741 $fields = $this->doGetFileXAttributes( $params );
742 $fields = is_array( $fields ) ? self
::normalizeXAttributes( $fields ) : false;
743 $this->cheapCache
->setField( $path, 'xattr', [ 'map' => $fields, 'latest' => $latest ] );
749 * @see FileBackendStore::getFileXAttributes()
750 * @param array $params
751 * @return array[][]|false
753 protected function doGetFileXAttributes( array $params ) {
754 return [ 'headers' => [], 'metadata' => [] ]; // not supported
757 final public function getFileSha1Base36( array $params ) {
758 $path = self
::normalizeStoragePath( $params['src'] );
759 if ( $path === null ) {
760 return false; // invalid storage path
762 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
763 $latest = !empty( $params['latest'] ); // use latest data?
764 if ( $this->cheapCache
->hasField( $path, 'sha1', self
::CACHE_TTL
) ) {
765 $stat = $this->cheapCache
->getField( $path, 'sha1' );
766 // If we want the latest data, check that this cached
767 // value was in fact fetched with the latest available data.
768 if ( !$latest ||
$stat['latest'] ) {
769 return $stat['hash'];
772 $hash = $this->doGetFileSha1Base36( $params );
773 $this->cheapCache
->setField( $path, 'sha1', [ 'hash' => $hash, 'latest' => $latest ] );
779 * @see FileBackendStore::getFileSha1Base36()
780 * @param array $params
781 * @return bool|string
783 protected function doGetFileSha1Base36( array $params ) {
784 $fsFile = $this->getLocalReference( $params );
788 return $fsFile->getSha1Base36();
792 final public function getFileProps( array $params ) {
793 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
794 $fsFile = $this->getLocalReference( $params );
795 $props = $fsFile ?
$fsFile->getProps() : FSFile
::placeholderProps();
800 final public function getLocalReferenceMulti( array $params ) {
801 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
803 $params = $this->setConcurrencyFlags( $params );
805 $fsFiles = []; // (path => FSFile)
806 $latest = !empty( $params['latest'] ); // use latest data?
807 // Reuse any files already in process cache...
808 foreach ( $params['srcs'] as $src ) {
809 $path = self
::normalizeStoragePath( $src );
810 if ( $path === null ) {
811 $fsFiles[$src] = null; // invalid storage path
812 } elseif ( $this->expensiveCache
->hasField( $path, 'localRef' ) ) {
813 $val = $this->expensiveCache
->getField( $path, 'localRef' );
814 // If we want the latest data, check that this cached
815 // value was in fact fetched with the latest available data.
816 if ( !$latest ||
$val['latest'] ) {
817 $fsFiles[$src] = $val['object'];
821 // Fetch local references of any remaning files...
822 $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
823 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
824 $fsFiles[$path] = $fsFile;
825 if ( $fsFile ) { // update the process cache...
826 $this->expensiveCache
->setField( $path, 'localRef',
827 [ 'object' => $fsFile, 'latest' => $latest ] );
835 * @see FileBackendStore::getLocalReferenceMulti()
836 * @param array $params
839 protected function doGetLocalReferenceMulti( array $params ) {
840 return $this->doGetLocalCopyMulti( $params );
843 final public function getLocalCopyMulti( array $params ) {
844 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
846 $params = $this->setConcurrencyFlags( $params );
847 $tmpFiles = $this->doGetLocalCopyMulti( $params );
853 * @see FileBackendStore::getLocalCopyMulti()
854 * @param array $params
857 abstract protected function doGetLocalCopyMulti( array $params );
860 * @see FileBackend::getFileHttpUrl()
861 * @param array $params
862 * @return string|null
864 public function getFileHttpUrl( array $params ) {
865 return null; // not supported
868 final public function streamFile( array $params ) {
869 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
870 $status = $this->newStatus();
872 // Always set some fields for subclass convenience
873 $params['options'] = $params['options'] ??
[];
874 $params['headers'] = $params['headers'] ??
[];
876 // Don't stream it out as text/html if there was a PHP error
877 if ( ( empty( $params['headless'] ) ||
$params['headers'] ) && headers_sent() ) {
878 print "Headers already sent, terminating.\n";
879 $status->fatal( 'backend-fail-stream', $params['src'] );
883 $status->merge( $this->doStreamFile( $params ) );
889 * @see FileBackendStore::streamFile()
890 * @param array $params
891 * @return StatusValue
893 protected function doStreamFile( array $params ) {
894 $status = $this->newStatus();
897 $flags |
= !empty( $params['headless'] ) ? HTTPFileStreamer
::STREAM_HEADLESS
: 0;
898 $flags |
= !empty( $params['allowOB'] ) ? HTTPFileStreamer
::STREAM_ALLOW_OB
: 0;
900 $fsFile = $this->getLocalReference( $params );
902 $streamer = new HTTPFileStreamer(
905 'obResetFunc' => $this->obResetFunc
,
906 'streamMimeFunc' => $this->streamMimeFunc
909 $res = $streamer->stream( $params['headers'], true, $params['options'], $flags );
912 HTTPFileStreamer
::send404Message( $params['src'], $flags );
916 $status->fatal( 'backend-fail-stream', $params['src'] );
922 final public function directoryExists( array $params ) {
923 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
924 if ( $dir === null ) {
925 return false; // invalid storage path
927 if ( $shard !== null ) { // confined to a single container/shard
928 return $this->doDirectoryExists( $fullCont, $dir, $params );
929 } else { // directory is on several shards
930 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
931 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
932 $res = false; // response
933 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
934 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
938 } elseif ( $exists === null ) { // error?
939 $res = null; // if we don't find anything, it is indeterminate
948 * @see FileBackendStore::directoryExists()
950 * @param string $container Resolved container name
951 * @param string $dir Resolved path relative to container
952 * @param array $params
955 abstract protected function doDirectoryExists( $container, $dir, array $params );
957 final public function getDirectoryList( array $params ) {
958 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
959 if ( $dir === null ) { // invalid storage path
962 if ( $shard !== null ) {
963 // File listing is confined to a single container/shard
964 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
966 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
967 // File listing spans multiple containers/shards
968 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
970 return new FileBackendStoreShardDirIterator( $this,
971 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
976 * Do not call this function from places outside FileBackend
978 * @see FileBackendStore::getDirectoryList()
980 * @param string $container Resolved container name
981 * @param string $dir Resolved path relative to container
982 * @param array $params
983 * @return Traversable|array|null Returns null on failure
985 abstract public function getDirectoryListInternal( $container, $dir, array $params );
987 final public function getFileList( array $params ) {
988 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
989 if ( $dir === null ) { // invalid storage path
992 if ( $shard !== null ) {
993 // File listing is confined to a single container/shard
994 return $this->getFileListInternal( $fullCont, $dir, $params );
996 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
997 // File listing spans multiple containers/shards
998 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
1000 return new FileBackendStoreShardFileIterator( $this,
1001 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
1006 * Do not call this function from places outside FileBackend
1008 * @see FileBackendStore::getFileList()
1010 * @param string $container Resolved container name
1011 * @param string $dir Resolved path relative to container
1012 * @param array $params
1013 * @return Traversable|string[]|null Returns null on failure
1015 abstract public function getFileListInternal( $container, $dir, array $params );
1018 * Return a list of FileOp objects from a list of operations.
1019 * Do not call this function from places outside FileBackend.
1021 * The result must have the same number of items as the input.
1022 * An exception is thrown if an unsupported operation is requested.
1024 * @param array $ops Same format as doOperations()
1025 * @return FileOp[] List of FileOp objects
1026 * @throws FileBackendError
1028 final public function getOperationsInternal( array $ops ) {
1030 'store' => StoreFileOp
::class,
1031 'copy' => CopyFileOp
::class,
1032 'move' => MoveFileOp
::class,
1033 'delete' => DeleteFileOp
::class,
1034 'create' => CreateFileOp
::class,
1035 'describe' => DescribeFileOp
::class,
1036 'null' => NullFileOp
::class
1039 $performOps = []; // array of FileOp objects
1040 // Build up ordered array of FileOps...
1041 foreach ( $ops as $operation ) {
1042 $opName = $operation['op'];
1043 if ( isset( $supportedOps[$opName] ) ) {
1044 $class = $supportedOps[$opName];
1045 // Get params for this operation
1046 $params = $operation;
1047 // Append the FileOp class
1048 $performOps[] = new $class( $this, $params, $this->logger
);
1050 throw new FileBackendError( "Operation '$opName' is not supported." );
1058 * Get a list of storage paths to lock for a list of operations
1059 * Returns an array with LockManager::LOCK_UW (shared locks) and
1060 * LockManager::LOCK_EX (exclusive locks) keys, each corresponding
1061 * to a list of storage paths to be locked. All returned paths are
1064 * @param array $performOps List of FileOp objects
1065 * @return array (LockManager::LOCK_UW => path list, LockManager::LOCK_EX => path list)
1067 final public function getPathsToLockForOpsInternal( array $performOps ) {
1068 // Build up a list of files to lock...
1069 $paths = [ 'sh' => [], 'ex' => [] ];
1070 foreach ( $performOps as $fileOp ) {
1071 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1072 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1074 // Optimization: if doing an EX lock anyway, don't also set an SH one
1075 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1076 // Get a shared lock on the parent directory of each path changed
1077 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1080 LockManager
::LOCK_UW
=> $paths['sh'],
1081 LockManager
::LOCK_EX
=> $paths['ex']
1085 public function getScopedLocksForOps( array $ops, StatusValue
$status ) {
1086 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1088 return $this->getScopedFileLocks( $paths, 'mixed', $status );
1091 final protected function doOperationsInternal( array $ops, array $opts ) {
1092 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1093 $status = $this->newStatus();
1095 // Fix up custom header name/value pairs...
1096 $ops = array_map( [ $this, 'sanitizeOpHeaders' ], $ops );
1098 // Build up a list of FileOps...
1099 $performOps = $this->getOperationsInternal( $ops );
1101 // Acquire any locks as needed...
1102 if ( empty( $opts['nonLocking'] ) ) {
1103 // Build up a list of files to lock...
1104 $paths = $this->getPathsToLockForOpsInternal( $performOps );
1105 // Try to lock those files for the scope of this function...
1107 $scopeLock = $this->getScopedFileLocks( $paths, 'mixed', $status );
1108 if ( !$status->isOK() ) {
1109 return $status; // abort
1113 // Clear any file cache entries (after locks acquired)
1114 if ( empty( $opts['preserveCache'] ) ) {
1115 $this->clearCache();
1118 // Build the list of paths involved
1120 foreach ( $performOps as $performOp ) {
1121 $paths = array_merge( $paths, $performOp->storagePathsRead() );
1122 $paths = array_merge( $paths, $performOp->storagePathsChanged() );
1125 // Enlarge the cache to fit the stat entries of these files
1126 $this->cheapCache
->setMaxSize( max( 2 * count( $paths ), self
::CACHE_CHEAP_SIZE
) );
1128 // Load from the persistent container caches
1129 $this->primeContainerCache( $paths );
1130 // Get the latest stat info for all the files (having locked them)
1131 $ok = $this->preloadFileStat( [ 'srcs' => $paths, 'latest' => true ] );
1134 // Actually attempt the operation batch...
1135 $opts = $this->setConcurrencyFlags( $opts );
1136 $subStatus = FileOpBatch
::attempt( $performOps, $opts, $this->fileJournal
);
1138 // If we could not even stat some files, then bail out...
1139 $subStatus = $this->newStatus( 'backend-fail-internal', $this->name
);
1140 foreach ( $ops as $i => $op ) { // mark each op as failed
1141 $subStatus->success
[$i] = false;
1142 ++
$subStatus->failCount
;
1144 $this->logger
->error( static::class . "-{$this->name} " .
1145 " stat failure; aborted operations: " . FormatJson
::encode( $ops ) );
1148 // Merge errors into StatusValue fields
1149 $status->merge( $subStatus );
1150 $status->success
= $subStatus->success
; // not done in merge()
1152 // Shrink the stat cache back to normal size
1153 $this->cheapCache
->setMaxSize( self
::CACHE_CHEAP_SIZE
);
1158 final protected function doQuickOperationsInternal( array $ops ) {
1159 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1160 $status = $this->newStatus();
1162 // Fix up custom header name/value pairs...
1163 $ops = array_map( [ $this, 'sanitizeOpHeaders' ], $ops );
1165 // Clear any file cache entries
1166 $this->clearCache();
1168 $supportedOps = [ 'create', 'store', 'copy', 'move', 'delete', 'describe', 'null' ];
1169 // Parallel ops may be disabled in config due to dependencies (e.g. needing popen())
1170 $async = ( $this->parallelize
=== 'implicit' && count( $ops ) > 1 );
1171 $maxConcurrency = $this->concurrency
; // throttle
1172 /** @var StatusValue[] $statuses */
1173 $statuses = []; // array of (index => StatusValue)
1174 $fileOpHandles = []; // list of (index => handle) arrays
1175 $curFileOpHandles = []; // current handle batch
1176 // Perform the sync-only ops and build up op handles for the async ops...
1177 foreach ( $ops as $index => $params ) {
1178 if ( !in_array( $params['op'], $supportedOps ) ) {
1179 throw new FileBackendError( "Operation '{$params['op']}' is not supported." );
1181 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1182 $subStatus = $this->$method( [ 'async' => $async ] +
$params );
1183 if ( $subStatus->value
instanceof FileBackendStoreOpHandle
) { // async
1184 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1185 $fileOpHandles[] = $curFileOpHandles; // push this batch
1186 $curFileOpHandles = [];
1188 $curFileOpHandles[$index] = $subStatus->value
; // keep index
1189 } else { // error or completed
1190 $statuses[$index] = $subStatus; // keep index
1193 if ( count( $curFileOpHandles ) ) {
1194 $fileOpHandles[] = $curFileOpHandles; // last batch
1196 // Do all the async ops that can be done concurrently...
1197 foreach ( $fileOpHandles as $fileHandleBatch ) {
1198 $statuses = $statuses +
$this->executeOpHandlesInternal( $fileHandleBatch );
1200 // Marshall and merge all the responses...
1201 foreach ( $statuses as $index => $subStatus ) {
1202 $status->merge( $subStatus );
1203 if ( $subStatus->isOK() ) {
1204 $status->success
[$index] = true;
1205 ++
$status->successCount
;
1207 $status->success
[$index] = false;
1208 ++
$status->failCount
;
1216 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1217 * The resulting StatusValue object fields will correspond
1218 * to the order in which the handles where given.
1220 * @param FileBackendStoreOpHandle[] $fileOpHandles
1221 * @return StatusValue[] Map of StatusValue objects
1222 * @throws FileBackendError
1224 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1225 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1227 foreach ( $fileOpHandles as $fileOpHandle ) {
1228 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle
) ) {
1229 throw new InvalidArgumentException( "Expected FileBackendStoreOpHandle object." );
1230 } elseif ( $fileOpHandle->backend
->getName() !== $this->getName() ) {
1231 throw new InvalidArgumentException( "Expected handle for this file backend." );
1235 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1236 foreach ( $fileOpHandles as $fileOpHandle ) {
1237 $fileOpHandle->closeResources();
1244 * @see FileBackendStore::executeOpHandlesInternal()
1246 * @param FileBackendStoreOpHandle[] $fileOpHandles
1248 * @throws FileBackendError
1249 * @return StatusValue[] List of corresponding StatusValue objects
1251 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1252 if ( count( $fileOpHandles ) ) {
1253 throw new LogicException( "Backend does not support asynchronous operations." );
1260 * Normalize and filter HTTP headers from a file operation
1262 * This normalizes and strips long HTTP headers from a file operation.
1263 * Most headers are just numbers, but some are allowed to be long.
1264 * This function is useful for cleaning up headers and avoiding backend
1265 * specific errors, especially in the middle of batch file operations.
1267 * @param array $op Same format as doOperation()
1270 protected function sanitizeOpHeaders( array $op ) {
1271 static $longs = [ 'content-disposition' ];
1273 if ( isset( $op['headers'] ) ) { // op sets HTTP headers
1275 foreach ( $op['headers'] as $name => $value ) {
1276 $name = strtolower( $name );
1277 $maxHVLen = in_array( $name, $longs ) ? INF
: 255;
1278 if ( strlen( $name ) > 255 ||
strlen( $value ) > $maxHVLen ) {
1279 trigger_error( "Header '$name: $value' is too long." );
1281 $newHeaders[$name] = strlen( $value ) ?
$value : ''; // null/false => ""
1284 $op['headers'] = $newHeaders;
1290 final public function preloadCache( array $paths ) {
1291 $fullConts = []; // full container names
1292 foreach ( $paths as $path ) {
1293 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1294 $fullConts[] = $fullCont;
1296 // Load from the persistent file and container caches
1297 $this->primeContainerCache( $fullConts );
1298 $this->primeFileCache( $paths );
1301 final public function clearCache( array $paths = null ) {
1302 if ( is_array( $paths ) ) {
1303 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1304 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1306 if ( $paths === null ) {
1307 $this->cheapCache
->clear();
1308 $this->expensiveCache
->clear();
1310 foreach ( $paths as $path ) {
1311 $this->cheapCache
->clear( $path );
1312 $this->expensiveCache
->clear( $path );
1315 $this->doClearCache( $paths );
1319 * Clears any additional stat caches for storage paths
1321 * @see FileBackend::clearCache()
1323 * @param array|null $paths Storage paths (optional)
1325 protected function doClearCache( array $paths = null ) {
1328 final public function preloadFileStat( array $params ) {
1329 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1330 $success = true; // no network errors
1332 $params['concurrency'] = ( $this->parallelize
!== 'off' ) ?
$this->concurrency
: 1;
1333 $stats = $this->doGetFileStatMulti( $params );
1334 if ( $stats === null ) {
1335 return true; // not supported
1338 $latest = !empty( $params['latest'] ); // use latest data?
1339 foreach ( $stats as $path => $stat ) {
1340 $path = FileBackend
::normalizeStoragePath( $path );
1341 if ( $path === null ) {
1342 continue; // this shouldn't happen
1344 if ( is_array( $stat ) ) { // file exists
1345 // Strongly consistent backends can automatically set "latest"
1346 $stat['latest'] = $stat['latest'] ??
$latest;
1347 $this->cheapCache
->setField( $path, 'stat', $stat );
1348 $this->setFileCache( $path, $stat ); // update persistent cache
1349 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
1350 $this->cheapCache
->setField( $path, 'sha1',
1351 [ 'hash' => $stat['sha1'], 'latest' => $latest ] );
1353 if ( isset( $stat['xattr'] ) ) { // some backends store headers/metadata
1354 $stat['xattr'] = self
::normalizeXAttributes( $stat['xattr'] );
1355 $this->cheapCache
->setField( $path, 'xattr',
1356 [ 'map' => $stat['xattr'], 'latest' => $latest ] );
1358 } elseif ( $stat === false ) { // file does not exist
1359 $this->cheapCache
->setField( $path, 'stat',
1360 $latest ?
'NOT_EXIST_LATEST' : 'NOT_EXIST' );
1361 $this->cheapCache
->setField( $path, 'xattr',
1362 [ 'map' => false, 'latest' => $latest ] );
1363 $this->cheapCache
->setField( $path, 'sha1',
1364 [ 'hash' => false, 'latest' => $latest ] );
1365 $this->logger
->debug( __METHOD__
. ': File {path} does not exist', [
1368 } else { // an error occurred
1370 $this->logger
->warning( __METHOD__
. ': Could not stat file {path}', [
1380 * Get file stat information (concurrently if possible) for several files
1382 * @see FileBackend::getFileStat()
1384 * @param array $params Parameters include:
1385 * - srcs : list of source storage paths
1386 * - latest : use the latest available data
1387 * @return array|null Map of storage paths to array|bool|null (returns null if not supported)
1390 protected function doGetFileStatMulti( array $params ) {
1391 return null; // not supported
1395 * Is this a key/value store where directories are just virtual?
1396 * Virtual directories exists in so much as files exists that are
1397 * prefixed with the directory path followed by a forward slash.
1401 abstract protected function directoriesAreVirtual();
1404 * Check if a short container name is valid
1406 * This checks for length and illegal characters.
1407 * This may disallow certain characters that can appear
1408 * in the prefix used to make the full container name.
1410 * @param string $container
1413 final protected static function isValidShortContainerName( $container ) {
1414 // Suffixes like '.xxx' (hex shard chars) or '.seg' (file segments)
1415 // might be used by subclasses. Reserve the dot character for sanity.
1416 // The only way dots end up in containers (e.g. resolveStoragePath)
1417 // is due to the wikiId container prefix or the above suffixes.
1418 return self
::isValidContainerName( $container ) && !preg_match( '/[.]/', $container );
1422 * Check if a full container name is valid
1424 * This checks for length and illegal characters.
1425 * Limiting the characters makes migrations to other stores easier.
1427 * @param string $container
1430 final protected static function isValidContainerName( $container ) {
1431 // This accounts for NTFS, Swift, and Ceph restrictions
1432 // and disallows directory separators or traversal characters.
1433 // Note that matching strings URL encode to the same string;
1434 // in Swift/Ceph, the length restriction is *after* URL encoding.
1435 return (bool)preg_match( '/^[a-z0-9][a-z0-9-_.]{0,199}$/i', $container );
1439 * Splits a storage path into an internal container name,
1440 * an internal relative file name, and a container shard suffix.
1441 * Any shard suffix is already appended to the internal container name.
1442 * This also checks that the storage path is valid and within this backend.
1444 * If the container is sharded but a suffix could not be determined,
1445 * this means that the path can only refer to a directory and can only
1446 * be scanned by looking in all the container shards.
1448 * @param string $storagePath
1449 * @return array (container, path, container suffix) or (null, null, null) if invalid
1451 final protected function resolveStoragePath( $storagePath ) {
1452 list( $backend, $shortCont, $relPath ) = self
::splitStoragePath( $storagePath );
1453 if ( $backend === $this->name
) { // must be for this backend
1454 $relPath = self
::normalizeContainerPath( $relPath );
1455 if ( $relPath !== null && self
::isValidShortContainerName( $shortCont ) ) {
1456 // Get shard for the normalized path if this container is sharded
1457 $cShard = $this->getContainerShard( $shortCont, $relPath );
1458 // Validate and sanitize the relative path (backend-specific)
1459 $relPath = $this->resolveContainerPath( $shortCont, $relPath );
1460 if ( $relPath !== null ) {
1461 // Prepend any wiki ID prefix to the container name
1462 $container = $this->fullContainerName( $shortCont );
1463 if ( self
::isValidContainerName( $container ) ) {
1464 // Validate and sanitize the container name (backend-specific)
1465 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1466 if ( $container !== null ) {
1467 return [ $container, $relPath, $cShard ];
1474 return [ null, null, null ];
1478 * Like resolveStoragePath() except null values are returned if
1479 * the container is sharded and the shard could not be determined
1480 * or if the path ends with '/'. The latter case is illegal for FS
1481 * backends and can confuse listings for object store backends.
1483 * This function is used when resolving paths that must be valid
1484 * locations for files. Directory and listing functions should
1485 * generally just use resolveStoragePath() instead.
1487 * @see FileBackendStore::resolveStoragePath()
1489 * @param string $storagePath
1490 * @return array (container, path) or (null, null) if invalid
1492 final protected function resolveStoragePathReal( $storagePath ) {
1493 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1494 if ( $cShard !== null && substr( $relPath, -1 ) !== '/' ) {
1495 return [ $container, $relPath ];
1498 return [ null, null ];
1502 * Get the container name shard suffix for a given path.
1503 * Any empty suffix means the container is not sharded.
1505 * @param string $container Container name
1506 * @param string $relPath Storage path relative to the container
1507 * @return string|null Returns null if shard could not be determined
1509 final protected function getContainerShard( $container, $relPath ) {
1510 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1511 if ( $levels == 1 ||
$levels == 2 ) {
1512 // Hash characters are either base 16 or 36
1513 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1514 // Get a regex that represents the shard portion of paths.
1515 // The concatenation of the captures gives us the shard.
1516 if ( $levels === 1 ) { // 16 or 36 shards per container
1517 $hashDirRegex = '(' . $char . ')';
1518 } else { // 256 or 1296 shards per container
1519 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1520 $hashDirRegex = $char . '/(' . $char . '{2})';
1521 } else { // short hash dir format (e.g. "a/b/c")
1522 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1525 // Allow certain directories to be above the hash dirs so as
1526 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1527 // They must be 2+ chars to avoid any hash directory ambiguity.
1529 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1530 return '.' . implode( '', array_slice( $m, 1 ) );
1533 return null; // failed to match
1536 return ''; // no sharding
1540 * Check if a storage path maps to a single shard.
1541 * Container dirs like "a", where the container shards on "x/xy",
1542 * can reside on several shards. Such paths are tricky to handle.
1544 * @param string $storagePath Storage path
1547 final public function isSingleShardPathInternal( $storagePath ) {
1548 list( , , $shard ) = $this->resolveStoragePath( $storagePath );
1550 return ( $shard !== null );
1554 * Get the sharding config for a container.
1555 * If greater than 0, then all file storage paths within
1556 * the container are required to be hashed accordingly.
1558 * @param string $container
1559 * @return array (integer levels, integer base, repeat flag) or (0, 0, false)
1561 final protected function getContainerHashLevels( $container ) {
1562 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1563 $config = $this->shardViaHashLevels
[$container];
1564 $hashLevels = (int)$config['levels'];
1565 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1566 $hashBase = (int)$config['base'];
1567 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1568 return [ $hashLevels, $hashBase, $config['repeat'] ];
1573 return [ 0, 0, false ]; // no sharding
1577 * Get a list of full container shard suffixes for a container
1579 * @param string $container
1582 final protected function getContainerSuffixes( $container ) {
1584 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1585 if ( $digits > 0 ) {
1586 $numShards = $base ** $digits;
1587 for ( $index = 0; $index < $numShards; $index++
) {
1588 $shards[] = '.' . Wikimedia\base_convert
( $index, 10, $base, $digits );
1596 * Get the full container name, including the wiki ID prefix
1598 * @param string $container
1601 final protected function fullContainerName( $container ) {
1602 if ( $this->domainId
!= '' ) {
1603 return "{$this->domainId}-$container";
1610 * Resolve a container name, checking if it's allowed by the backend.
1611 * This is intended for internal use, such as encoding illegal chars.
1612 * Subclasses can override this to be more restrictive.
1614 * @param string $container
1615 * @return string|null
1617 protected function resolveContainerName( $container ) {
1622 * Resolve a relative storage path, checking if it's allowed by the backend.
1623 * This is intended for internal use, such as encoding illegal chars or perhaps
1624 * getting absolute paths (e.g. FS based backends). Note that the relative path
1625 * may be the empty string (e.g. the path is simply to the container).
1627 * @param string $container Container name
1628 * @param string $relStoragePath Storage path relative to the container
1629 * @return string|null Path or null if not valid
1631 protected function resolveContainerPath( $container, $relStoragePath ) {
1632 return $relStoragePath;
1636 * Get the cache key for a container
1638 * @param string $container Resolved container name
1641 private function containerCacheKey( $container ) {
1642 return "filebackend:{$this->name}:{$this->domainId}:container:{$container}";
1646 * Set the cached info for a container
1648 * @param string $container Resolved container name
1649 * @param array $val Information to cache
1651 final protected function setContainerCache( $container, array $val ) {
1652 $this->memCache
->set( $this->containerCacheKey( $container ), $val, 14 * 86400 );
1656 * Delete the cached info for a container.
1657 * The cache key is salted for a while to prevent race conditions.
1659 * @param string $container Resolved container name
1661 final protected function deleteContainerCache( $container ) {
1662 if ( !$this->memCache
->delete( $this->containerCacheKey( $container ), 300 ) ) {
1663 trigger_error( "Unable to delete stat cache for container $container." );
1668 * Do a batch lookup from cache for container stats for all containers
1669 * used in a list of container names or storage paths objects.
1670 * This loads the persistent cache values into the process cache.
1672 * @param array $items
1674 final protected function primeContainerCache( array $items ) {
1675 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1677 $paths = []; // list of storage paths
1678 $contNames = []; // (cache key => resolved container name)
1679 // Get all the paths/containers from the items...
1680 foreach ( $items as $item ) {
1681 if ( self
::isStoragePath( $item ) ) {
1683 } elseif ( is_string( $item ) ) { // full container name
1684 $contNames[$this->containerCacheKey( $item )] = $item;
1687 // Get all the corresponding cache keys for paths...
1688 foreach ( $paths as $path ) {
1689 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1690 if ( $fullCont !== null ) { // valid path for this backend
1691 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1695 $contInfo = []; // (resolved container name => cache value)
1696 // Get all cache entries for these container cache keys...
1697 $values = $this->memCache
->getMulti( array_keys( $contNames ) );
1698 foreach ( $values as $cacheKey => $val ) {
1699 $contInfo[$contNames[$cacheKey]] = $val;
1702 // Populate the container process cache for the backend...
1703 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1707 * Fill the backend-specific process cache given an array of
1708 * resolved container names and their corresponding cached info.
1709 * Only containers that actually exist should appear in the map.
1711 * @param array $containerInfo Map of resolved container names to cached info
1713 protected function doPrimeContainerCache( array $containerInfo ) {
1717 * Get the cache key for a file path
1719 * @param string $path Normalized storage path
1722 private function fileCacheKey( $path ) {
1723 return "filebackend:{$this->name}:{$this->domainId}:file:" . sha1( $path );
1727 * Set the cached stat info for a file path.
1728 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1729 * salting for the case when a file is created at a path were there was none before.
1731 * @param string $path Storage path
1732 * @param array $val Stat information to cache
1734 final protected function setFileCache( $path, array $val ) {
1735 $path = FileBackend
::normalizeStoragePath( $path );
1736 if ( $path === null ) {
1737 return; // invalid storage path
1739 $mtime = ConvertibleTimestamp
::convert( TS_UNIX
, $val['mtime'] );
1740 $ttl = $this->memCache
->adaptiveTTL( $mtime, 7 * 86400, 300, 0.1 );
1741 $key = $this->fileCacheKey( $path );
1742 // Set the cache unless it is currently salted.
1743 $this->memCache
->set( $key, $val, $ttl );
1747 * Delete the cached stat info for a file path.
1748 * The cache key is salted for a while to prevent race conditions.
1749 * Since negatives (404s) are not cached, this does not need to be called when
1750 * a file is created at a path were there was none before.
1752 * @param string $path Storage path
1754 final protected function deleteFileCache( $path ) {
1755 $path = FileBackend
::normalizeStoragePath( $path );
1756 if ( $path === null ) {
1757 return; // invalid storage path
1759 if ( !$this->memCache
->delete( $this->fileCacheKey( $path ), 300 ) ) {
1760 trigger_error( "Unable to delete stat cache for file $path." );
1765 * Do a batch lookup from cache for file stats for all paths
1766 * used in a list of storage paths or FileOp objects.
1767 * This loads the persistent cache values into the process cache.
1769 * @param array $items List of storage paths
1771 final protected function primeFileCache( array $items ) {
1772 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1774 $paths = []; // list of storage paths
1775 $pathNames = []; // (cache key => storage path)
1776 // Get all the paths/containers from the items...
1777 foreach ( $items as $item ) {
1778 if ( self
::isStoragePath( $item ) ) {
1779 $paths[] = FileBackend
::normalizeStoragePath( $item );
1782 // Get rid of any paths that failed normalization...
1783 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1784 // Get all the corresponding cache keys for paths...
1785 foreach ( $paths as $path ) {
1786 list( , $rel, ) = $this->resolveStoragePath( $path );
1787 if ( $rel !== null ) { // valid path for this backend
1788 $pathNames[$this->fileCacheKey( $path )] = $path;
1791 // Get all cache entries for these file cache keys...
1792 $values = $this->memCache
->getMulti( array_keys( $pathNames ) );
1793 foreach ( $values as $cacheKey => $val ) {
1794 $path = $pathNames[$cacheKey];
1795 if ( is_array( $val ) ) {
1796 $val['latest'] = false; // never completely trust cache
1797 $this->cheapCache
->setField( $path, 'stat', $val );
1798 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1799 $this->cheapCache
->setField( $path, 'sha1',
1800 [ 'hash' => $val['sha1'], 'latest' => false ] );
1802 if ( isset( $val['xattr'] ) ) { // some backends store headers/metadata
1803 $val['xattr'] = self
::normalizeXAttributes( $val['xattr'] );
1804 $this->cheapCache
->setField( $path, 'xattr',
1805 [ 'map' => $val['xattr'], 'latest' => false ] );
1812 * Normalize file headers/metadata to the FileBackend::getFileXAttributes() format
1814 * @param array $xattr
1818 final protected static function normalizeXAttributes( array $xattr ) {
1819 $newXAttr = [ 'headers' => [], 'metadata' => [] ];
1821 foreach ( $xattr['headers'] as $name => $value ) {
1822 $newXAttr['headers'][strtolower( $name )] = $value;
1825 foreach ( $xattr['metadata'] as $name => $value ) {
1826 $newXAttr['metadata'][strtolower( $name )] = $value;
1833 * Set the 'concurrency' option from a list of operation options
1835 * @param array $opts Map of operation options
1838 final protected function setConcurrencyFlags( array $opts ) {
1839 $opts['concurrency'] = 1; // off
1840 if ( $this->parallelize
=== 'implicit' ) {
1841 if ( !isset( $opts['parallelize'] ) ||
$opts['parallelize'] ) {
1842 $opts['concurrency'] = $this->concurrency
;
1844 } elseif ( $this->parallelize
=== 'explicit' ) {
1845 if ( !empty( $opts['parallelize'] ) ) {
1846 $opts['concurrency'] = $this->concurrency
;
1854 * Get the content type to use in HEAD/GET requests for a file
1856 * @param string $storagePath
1857 * @param string|null $content File data
1858 * @param string|null $fsPath File system path
1859 * @return string MIME type
1861 protected function getContentType( $storagePath, $content, $fsPath ) {
1862 if ( $this->mimeCallback
) {
1863 return call_user_func_array( $this->mimeCallback
, func_get_args() );
1866 $mime = ( $fsPath !== null ) ?
mime_content_type( $fsPath ) : false;
1867 return $mime ?
: 'unknown/unknown';