3 * Base class for all backends using particular storage medium.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup FileBackend
23 use Wikimedia\Timestamp\ConvertibleTimestamp
;
26 * @brief Base class for all backends using particular storage medium.
28 * This class defines the methods as abstract that subclasses must implement.
29 * Outside callers should *not* use functions with "Internal" in the name.
31 * The FileBackend operations are implemented using basic functions
32 * such as storeInternal(), copyInternal(), deleteInternal() and the like.
33 * This class is also responsible for path resolution and sanitization.
35 * @ingroup FileBackend
38 abstract class FileBackendStore
extends FileBackend
{
39 /** @var WANObjectCache */
43 /** @var MapCacheLRU Map of paths to small (RAM/disk) cache items */
44 protected $cheapCache;
45 /** @var MapCacheLRU Map of paths to large (RAM/disk) cache items */
46 protected $expensiveCache;
48 /** @var array Map of container names to sharding config */
49 protected $shardViaHashLevels = [];
51 /** @var callable Method to get the MIME type of files */
52 protected $mimeCallback;
54 protected $maxFileSize = 4294967296; // integer bytes (4GiB)
56 const CACHE_TTL
= 10; // integer; TTL in seconds for process cache entries
57 const CACHE_CHEAP_SIZE
= 500; // integer; max entries in "cheap cache"
58 const CACHE_EXPENSIVE_SIZE
= 5; // integer; max entries in "expensive cache"
61 * @see FileBackend::__construct()
62 * Additional $config params include:
63 * - srvCache : BagOStuff cache to APC or the like.
64 * - wanCache : WANObjectCache object to use for persistent caching.
65 * - mimeCallback : Callback that takes (storage path, content, file system path) and
66 * returns the MIME type of the file or 'unknown/unknown'. The file
67 * system path parameter should be used if the content one is null.
69 * @param array $config
71 public function __construct( array $config ) {
72 parent
::__construct( $config );
73 $this->mimeCallback
= $config['mimeCallback'] ??
null;
74 $this->srvCache
= new EmptyBagOStuff(); // disabled by default
75 $this->memCache
= WANObjectCache
::newEmpty(); // disabled by default
76 $this->cheapCache
= new MapCacheLRU( self
::CACHE_CHEAP_SIZE
);
77 $this->expensiveCache
= new MapCacheLRU( self
::CACHE_EXPENSIVE_SIZE
);
81 * Get the maximum allowable file size given backend
82 * medium restrictions and basic performance constraints.
83 * Do not call this function from places outside FileBackend and FileOp.
87 final public function maxFileSizeInternal() {
88 return $this->maxFileSize
;
92 * Check if a file can be created or changed at a given storage path.
93 * FS backends should check if the parent directory exists, files can be
94 * written under it, and that any file already there is writable.
95 * Backends using key/value stores should check if the container exists.
97 * @param string $storagePath
100 abstract public function isPathUsableInternal( $storagePath );
103 * Create a file in the backend with the given contents.
104 * This will overwrite any file that exists at the destination.
105 * Do not call this function from places outside FileBackend and FileOp.
108 * - content : the raw file contents
109 * - dst : destination storage path
110 * - headers : HTTP header name/value map
111 * - async : StatusValue will be returned immediately if supported.
112 * If the StatusValue is OK, then its value field will be
113 * set to a FileBackendStoreOpHandle object.
114 * - dstExists : Whether a file exists at the destination (optimization).
115 * Callers can use "false" if no existing file is being changed.
117 * @param array $params
118 * @return StatusValue
120 final public function createInternal( array $params ) {
121 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
122 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
123 $status = $this->newStatus( 'backend-fail-maxsize',
124 $params['dst'], $this->maxFileSizeInternal() );
126 $status = $this->doCreateInternal( $params );
127 $this->clearCache( [ $params['dst'] ] );
128 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
129 $this->deleteFileCache( $params['dst'] ); // persistent cache
137 * @see FileBackendStore::createInternal()
138 * @param array $params
139 * @return StatusValue
141 abstract protected function doCreateInternal( array $params );
144 * Store a file into the backend from a file on disk.
145 * This will overwrite any file that exists at the destination.
146 * Do not call this function from places outside FileBackend and FileOp.
149 * - src : source path on disk
150 * - dst : destination storage path
151 * - headers : HTTP header name/value map
152 * - async : StatusValue will be returned immediately if supported.
153 * If the StatusValue is OK, then its value field will be
154 * set to a FileBackendStoreOpHandle object.
155 * - dstExists : Whether a file exists at the destination (optimization).
156 * Callers can use "false" if no existing file is being changed.
158 * @param array $params
159 * @return StatusValue
161 final public function storeInternal( array $params ) {
162 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
163 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
164 $status = $this->newStatus( 'backend-fail-maxsize',
165 $params['dst'], $this->maxFileSizeInternal() );
167 $status = $this->doStoreInternal( $params );
168 $this->clearCache( [ $params['dst'] ] );
169 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
170 $this->deleteFileCache( $params['dst'] ); // persistent cache
178 * @see FileBackendStore::storeInternal()
179 * @param array $params
180 * @return StatusValue
182 abstract protected function doStoreInternal( array $params );
185 * Copy a file from one storage path to another in the backend.
186 * This will overwrite any file that exists at the destination.
187 * Do not call this function from places outside FileBackend and FileOp.
190 * - src : source storage path
191 * - dst : destination storage path
192 * - ignoreMissingSource : do nothing if the source file does not exist
193 * - headers : HTTP header name/value map
194 * - async : StatusValue will be returned immediately if supported.
195 * If the StatusValue is OK, then its value field will be
196 * set to a FileBackendStoreOpHandle object.
197 * - dstExists : Whether a file exists at the destination (optimization).
198 * Callers can use "false" if no existing file is being changed.
200 * @param array $params
201 * @return StatusValue
203 final public function copyInternal( array $params ) {
204 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
205 $status = $this->doCopyInternal( $params );
206 $this->clearCache( [ $params['dst'] ] );
207 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
208 $this->deleteFileCache( $params['dst'] ); // persistent cache
215 * @see FileBackendStore::copyInternal()
216 * @param array $params
217 * @return StatusValue
219 abstract protected function doCopyInternal( array $params );
222 * Delete a file at the storage path.
223 * Do not call this function from places outside FileBackend and FileOp.
226 * - src : source storage path
227 * - ignoreMissingSource : do nothing if the source file does not exist
228 * - async : StatusValue will be returned immediately if supported.
229 * If the StatusValue is OK, then its value field will be
230 * set to a FileBackendStoreOpHandle object.
232 * @param array $params
233 * @return StatusValue
235 final public function deleteInternal( array $params ) {
236 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
237 $status = $this->doDeleteInternal( $params );
238 $this->clearCache( [ $params['src'] ] );
239 $this->deleteFileCache( $params['src'] ); // persistent cache
244 * @see FileBackendStore::deleteInternal()
245 * @param array $params
246 * @return StatusValue
248 abstract protected function doDeleteInternal( array $params );
251 * Move a file from one storage path to another in the backend.
252 * This will overwrite any file that exists at the destination.
253 * Do not call this function from places outside FileBackend and FileOp.
256 * - src : source storage path
257 * - dst : destination storage path
258 * - ignoreMissingSource : do nothing if the source file does not exist
259 * - headers : HTTP header name/value map
260 * - async : StatusValue will be returned immediately if supported.
261 * If the StatusValue is OK, then its value field will be
262 * set to a FileBackendStoreOpHandle object.
263 * - dstExists : Whether a file exists at the destination (optimization).
264 * Callers can use "false" if no existing file is being changed.
266 * @param array $params
267 * @return StatusValue
269 final public function moveInternal( array $params ) {
270 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
271 $status = $this->doMoveInternal( $params );
272 $this->clearCache( [ $params['src'], $params['dst'] ] );
273 $this->deleteFileCache( $params['src'] ); // persistent cache
274 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
275 $this->deleteFileCache( $params['dst'] ); // persistent cache
282 * @see FileBackendStore::moveInternal()
283 * @param array $params
284 * @return StatusValue
286 protected function doMoveInternal( array $params ) {
287 unset( $params['async'] ); // two steps, won't work here :)
288 $nsrc = FileBackend
::normalizeStoragePath( $params['src'] );
289 $ndst = FileBackend
::normalizeStoragePath( $params['dst'] );
290 // Copy source to dest
291 $status = $this->copyInternal( $params );
292 if ( $nsrc !== $ndst && $status->isOK() ) {
293 // Delete source (only fails due to races or network problems)
294 $status->merge( $this->deleteInternal( [ 'src' => $params['src'] ] ) );
295 $status->setResult( true, $status->value
); // ignore delete() errors
302 * Alter metadata for a file at the storage path.
303 * Do not call this function from places outside FileBackend and FileOp.
306 * - src : source storage path
307 * - headers : HTTP header name/value map
308 * - async : StatusValue will be returned immediately if supported.
309 * If the StatusValue is OK, then its value field will be
310 * set to a FileBackendStoreOpHandle object.
312 * @param array $params
313 * @return StatusValue
315 final public function describeInternal( array $params ) {
316 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
317 if ( count( $params['headers'] ) ) {
318 $status = $this->doDescribeInternal( $params );
319 $this->clearCache( [ $params['src'] ] );
320 $this->deleteFileCache( $params['src'] ); // persistent cache
322 $status = $this->newStatus(); // nothing to do
329 * @see FileBackendStore::describeInternal()
330 * @param array $params
331 * @return StatusValue
333 protected function doDescribeInternal( array $params ) {
334 return $this->newStatus();
338 * No-op file operation that does nothing.
339 * Do not call this function from places outside FileBackend and FileOp.
341 * @param array $params
342 * @return StatusValue
344 final public function nullInternal( array $params ) {
345 return $this->newStatus();
348 final public function concatenate( array $params ) {
349 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
350 $status = $this->newStatus();
352 // Try to lock the source files for the scope of this function
353 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager
::LOCK_UW
, $status );
354 if ( $status->isOK() ) {
355 // Actually do the file concatenation...
356 $start_time = microtime( true );
357 $status->merge( $this->doConcatenate( $params ) );
358 $sec = microtime( true ) - $start_time;
359 if ( !$status->isOK() ) {
360 $this->logger
->error( static::class . "-{$this->name}" .
361 " failed to concatenate " . count( $params['srcs'] ) . " file(s) [$sec sec]" );
369 * @see FileBackendStore::concatenate()
370 * @param array $params
371 * @return StatusValue
373 protected function doConcatenate( array $params ) {
374 $status = $this->newStatus();
375 $tmpPath = $params['dst']; // convenience
376 unset( $params['latest'] ); // sanity
378 // Check that the specified temp file is valid...
379 Wikimedia\
suppressWarnings();
380 $ok = ( is_file( $tmpPath ) && filesize( $tmpPath ) == 0 );
381 Wikimedia\restoreWarnings
();
382 if ( !$ok ) { // not present or not empty
383 $status->fatal( 'backend-fail-opentemp', $tmpPath );
388 // Get local FS versions of the chunks needed for the concatenation...
389 $fsFiles = $this->getLocalReferenceMulti( $params );
390 foreach ( $fsFiles as $path => &$fsFile ) {
391 if ( !$fsFile ) { // chunk failed to download?
392 $fsFile = $this->getLocalReference( [ 'src' => $path ] );
393 if ( !$fsFile ) { // retry failed?
394 $status->fatal( 'backend-fail-read', $path );
400 unset( $fsFile ); // unset reference so we can reuse $fsFile
402 // Get a handle for the destination temp file
403 $tmpHandle = fopen( $tmpPath, 'ab' );
404 if ( $tmpHandle === false ) {
405 $status->fatal( 'backend-fail-opentemp', $tmpPath );
410 // Build up the temp file using the source chunks (in order)...
411 foreach ( $fsFiles as $virtualSource => $fsFile ) {
412 // Get a handle to the local FS version
413 $sourceHandle = fopen( $fsFile->getPath(), 'rb' );
414 if ( $sourceHandle === false ) {
415 fclose( $tmpHandle );
416 $status->fatal( 'backend-fail-read', $virtualSource );
420 // Append chunk to file (pass chunk size to avoid magic quotes)
421 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
422 fclose( $sourceHandle );
423 fclose( $tmpHandle );
424 $status->fatal( 'backend-fail-writetemp', $tmpPath );
428 fclose( $sourceHandle );
430 if ( !fclose( $tmpHandle ) ) {
431 $status->fatal( 'backend-fail-closetemp', $tmpPath );
436 clearstatcache(); // temp file changed
441 final protected function doPrepare( array $params ) {
442 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
443 $status = $this->newStatus();
445 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
446 if ( $dir === null ) {
447 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
449 return $status; // invalid storage path
452 if ( $shard !== null ) { // confined to a single container/shard
453 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
454 } else { // directory is on several shards
455 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
456 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
457 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
458 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
466 * @see FileBackendStore::doPrepare()
467 * @param string $container
469 * @param array $params
470 * @return StatusValue
472 protected function doPrepareInternal( $container, $dir, array $params ) {
473 return $this->newStatus();
476 final protected function doSecure( array $params ) {
477 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
478 $status = $this->newStatus();
480 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
481 if ( $dir === null ) {
482 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
484 return $status; // invalid storage path
487 if ( $shard !== null ) { // confined to a single container/shard
488 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
489 } else { // directory is on several shards
490 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
491 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
492 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
493 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
501 * @see FileBackendStore::doSecure()
502 * @param string $container
504 * @param array $params
505 * @return StatusValue
507 protected function doSecureInternal( $container, $dir, array $params ) {
508 return $this->newStatus();
511 final protected function doPublish( array $params ) {
512 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
513 $status = $this->newStatus();
515 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
516 if ( $dir === null ) {
517 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
519 return $status; // invalid storage path
522 if ( $shard !== null ) { // confined to a single container/shard
523 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
524 } else { // directory is on several shards
525 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
526 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
527 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
528 $status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
536 * @see FileBackendStore::doPublish()
537 * @param string $container
539 * @param array $params
540 * @return StatusValue
542 protected function doPublishInternal( $container, $dir, array $params ) {
543 return $this->newStatus();
546 final protected function doClean( array $params ) {
547 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
548 $status = $this->newStatus();
550 // Recursive: first delete all empty subdirs recursively
551 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
552 $subDirsRel = $this->getTopDirectoryList( [ 'dir' => $params['dir'] ] );
553 if ( $subDirsRel !== null ) { // no errors
554 foreach ( $subDirsRel as $subDirRel ) {
555 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
556 $status->merge( $this->doClean( [ 'dir' => $subDir ] +
$params ) );
558 unset( $subDirsRel ); // free directory for rmdir() on Windows (for FS backends)
562 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
563 if ( $dir === null ) {
564 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
566 return $status; // invalid storage path
569 // Attempt to lock this directory...
570 $filesLockEx = [ $params['dir'] ];
571 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
572 if ( !$status->isOK() ) {
573 return $status; // abort
576 if ( $shard !== null ) { // confined to a single container/shard
577 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
578 $this->deleteContainerCache( $fullCont ); // purge cache
579 } else { // directory is on several shards
580 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
581 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
582 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
583 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
584 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
592 * @see FileBackendStore::doClean()
593 * @param string $container
595 * @param array $params
596 * @return StatusValue
598 protected function doCleanInternal( $container, $dir, array $params ) {
599 return $this->newStatus();
602 final public function fileExists( array $params ) {
603 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
604 $stat = $this->getFileStat( $params );
606 return ( $stat === null ) ?
null : (bool)$stat; // null => failure
609 final public function getFileTimestamp( array $params ) {
610 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
611 $stat = $this->getFileStat( $params );
613 return $stat ?
$stat['mtime'] : false;
616 final public function getFileSize( array $params ) {
617 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
618 $stat = $this->getFileStat( $params );
620 return $stat ?
$stat['size'] : false;
623 final public function getFileStat( array $params ) {
624 $path = self
::normalizeStoragePath( $params['src'] );
625 if ( $path === null ) {
626 return false; // invalid storage path
628 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
629 $latest = !empty( $params['latest'] ); // use latest data?
630 if ( !$latest && !$this->cheapCache
->hasField( $path, 'stat', self
::CACHE_TTL
) ) {
631 $this->primeFileCache( [ $path ] ); // check persistent cache
633 if ( $this->cheapCache
->hasField( $path, 'stat', self
::CACHE_TTL
) ) {
634 $stat = $this->cheapCache
->getField( $path, 'stat' );
635 // If we want the latest data, check that this cached
636 // value was in fact fetched with the latest available data.
637 if ( is_array( $stat ) ) {
638 if ( !$latest ||
$stat['latest'] ) {
641 } elseif ( in_array( $stat, [ 'NOT_EXIST', 'NOT_EXIST_LATEST' ] ) ) {
642 if ( !$latest ||
$stat === 'NOT_EXIST_LATEST' ) {
647 $stat = $this->doGetFileStat( $params );
648 if ( is_array( $stat ) ) { // file exists
649 // Strongly consistent backends can automatically set "latest"
650 $stat['latest'] = $stat['latest'] ??
$latest;
651 $this->cheapCache
->setField( $path, 'stat', $stat );
652 $this->setFileCache( $path, $stat ); // update persistent cache
653 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
654 $this->cheapCache
->setField( $path, 'sha1',
655 [ 'hash' => $stat['sha1'], 'latest' => $latest ] );
657 if ( isset( $stat['xattr'] ) ) { // some backends store headers/metadata
658 $stat['xattr'] = self
::normalizeXAttributes( $stat['xattr'] );
659 $this->cheapCache
->setField( $path, 'xattr',
660 [ 'map' => $stat['xattr'], 'latest' => $latest ] );
662 } elseif ( $stat === false ) { // file does not exist
663 $this->cheapCache
->setField( $path, 'stat', $latest ?
'NOT_EXIST_LATEST' : 'NOT_EXIST' );
664 $this->cheapCache
->setField( $path, 'xattr', [ 'map' => false, 'latest' => $latest ] );
665 $this->cheapCache
->setField( $path, 'sha1', [ 'hash' => false, 'latest' => $latest ] );
666 $this->logger
->debug( __METHOD__
. ': File {path} does not exist', [
669 } else { // an error occurred
670 $this->logger
->warning( __METHOD__
. ': Could not stat file {path}', [
679 * @see FileBackendStore::getFileStat()
680 * @param array $params
682 abstract protected function doGetFileStat( array $params );
684 public function getFileContentsMulti( array $params ) {
685 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
687 $params = $this->setConcurrencyFlags( $params );
688 $contents = $this->doGetFileContentsMulti( $params );
694 * @see FileBackendStore::getFileContentsMulti()
695 * @param array $params
698 protected function doGetFileContentsMulti( array $params ) {
700 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
701 Wikimedia\
suppressWarnings();
702 $contents[$path] = $fsFile ?
file_get_contents( $fsFile->getPath() ) : false;
703 Wikimedia\restoreWarnings
();
709 final public function getFileXAttributes( array $params ) {
710 $path = self
::normalizeStoragePath( $params['src'] );
711 if ( $path === null ) {
712 return false; // invalid storage path
714 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
715 $latest = !empty( $params['latest'] ); // use latest data?
716 if ( $this->cheapCache
->hasField( $path, 'xattr', self
::CACHE_TTL
) ) {
717 $stat = $this->cheapCache
->getField( $path, 'xattr' );
718 // If we want the latest data, check that this cached
719 // value was in fact fetched with the latest available data.
720 if ( !$latest ||
$stat['latest'] ) {
724 $fields = $this->doGetFileXAttributes( $params );
725 $fields = is_array( $fields ) ? self
::normalizeXAttributes( $fields ) : false;
726 $this->cheapCache
->setField( $path, 'xattr', [ 'map' => $fields, 'latest' => $latest ] );
732 * @see FileBackendStore::getFileXAttributes()
733 * @param array $params
736 protected function doGetFileXAttributes( array $params ) {
737 return [ 'headers' => [], 'metadata' => [] ]; // not supported
740 final public function getFileSha1Base36( array $params ) {
741 $path = self
::normalizeStoragePath( $params['src'] );
742 if ( $path === null ) {
743 return false; // invalid storage path
745 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
746 $latest = !empty( $params['latest'] ); // use latest data?
747 if ( $this->cheapCache
->hasField( $path, 'sha1', self
::CACHE_TTL
) ) {
748 $stat = $this->cheapCache
->getField( $path, 'sha1' );
749 // If we want the latest data, check that this cached
750 // value was in fact fetched with the latest available data.
751 if ( !$latest ||
$stat['latest'] ) {
752 return $stat['hash'];
755 $hash = $this->doGetFileSha1Base36( $params );
756 $this->cheapCache
->setField( $path, 'sha1', [ 'hash' => $hash, 'latest' => $latest ] );
762 * @see FileBackendStore::getFileSha1Base36()
763 * @param array $params
764 * @return bool|string
766 protected function doGetFileSha1Base36( array $params ) {
767 $fsFile = $this->getLocalReference( $params );
771 return $fsFile->getSha1Base36();
775 final public function getFileProps( array $params ) {
776 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
777 $fsFile = $this->getLocalReference( $params );
778 $props = $fsFile ?
$fsFile->getProps() : FSFile
::placeholderProps();
783 final public function getLocalReferenceMulti( array $params ) {
784 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
786 $params = $this->setConcurrencyFlags( $params );
788 $fsFiles = []; // (path => FSFile)
789 $latest = !empty( $params['latest'] ); // use latest data?
790 // Reuse any files already in process cache...
791 foreach ( $params['srcs'] as $src ) {
792 $path = self
::normalizeStoragePath( $src );
793 if ( $path === null ) {
794 $fsFiles[$src] = null; // invalid storage path
795 } elseif ( $this->expensiveCache
->hasField( $path, 'localRef' ) ) {
796 $val = $this->expensiveCache
->getField( $path, 'localRef' );
797 // If we want the latest data, check that this cached
798 // value was in fact fetched with the latest available data.
799 if ( !$latest ||
$val['latest'] ) {
800 $fsFiles[$src] = $val['object'];
804 // Fetch local references of any remaning files...
805 $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
806 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
807 $fsFiles[$path] = $fsFile;
808 if ( $fsFile ) { // update the process cache...
809 $this->expensiveCache
->setField( $path, 'localRef',
810 [ 'object' => $fsFile, 'latest' => $latest ] );
818 * @see FileBackendStore::getLocalReferenceMulti()
819 * @param array $params
822 protected function doGetLocalReferenceMulti( array $params ) {
823 return $this->doGetLocalCopyMulti( $params );
826 final public function getLocalCopyMulti( array $params ) {
827 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
829 $params = $this->setConcurrencyFlags( $params );
830 $tmpFiles = $this->doGetLocalCopyMulti( $params );
836 * @see FileBackendStore::getLocalCopyMulti()
837 * @param array $params
840 abstract protected function doGetLocalCopyMulti( array $params );
843 * @see FileBackend::getFileHttpUrl()
844 * @param array $params
845 * @return string|null
847 public function getFileHttpUrl( array $params ) {
848 return null; // not supported
851 final public function streamFile( array $params ) {
852 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
853 $status = $this->newStatus();
855 // Always set some fields for subclass convenience
856 $params['options'] = $params['options'] ??
[];
857 $params['headers'] = $params['headers'] ??
[];
859 // Don't stream it out as text/html if there was a PHP error
860 if ( ( empty( $params['headless'] ) ||
$params['headers'] ) && headers_sent() ) {
861 print "Headers already sent, terminating.\n";
862 $status->fatal( 'backend-fail-stream', $params['src'] );
866 $status->merge( $this->doStreamFile( $params ) );
872 * @see FileBackendStore::streamFile()
873 * @param array $params
874 * @return StatusValue
876 protected function doStreamFile( array $params ) {
877 $status = $this->newStatus();
880 $flags |
= !empty( $params['headless'] ) ? HTTPFileStreamer
::STREAM_HEADLESS
: 0;
881 $flags |
= !empty( $params['allowOB'] ) ? HTTPFileStreamer
::STREAM_ALLOW_OB
: 0;
883 $fsFile = $this->getLocalReference( $params );
885 $streamer = new HTTPFileStreamer(
888 'obResetFunc' => $this->obResetFunc
,
889 'streamMimeFunc' => $this->streamMimeFunc
892 $res = $streamer->stream( $params['headers'], true, $params['options'], $flags );
895 HTTPFileStreamer
::send404Message( $params['src'], $flags );
899 $status->fatal( 'backend-fail-stream', $params['src'] );
905 final public function directoryExists( array $params ) {
906 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
907 if ( $dir === null ) {
908 return false; // invalid storage path
910 if ( $shard !== null ) { // confined to a single container/shard
911 return $this->doDirectoryExists( $fullCont, $dir, $params );
912 } else { // directory is on several shards
913 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
914 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
915 $res = false; // response
916 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
917 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
921 } elseif ( $exists === null ) { // error?
922 $res = null; // if we don't find anything, it is indeterminate
931 * @see FileBackendStore::directoryExists()
933 * @param string $container Resolved container name
934 * @param string $dir Resolved path relative to container
935 * @param array $params
938 abstract protected function doDirectoryExists( $container, $dir, array $params );
940 final public function getDirectoryList( array $params ) {
941 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
942 if ( $dir === null ) { // invalid storage path
945 if ( $shard !== null ) {
946 // File listing is confined to a single container/shard
947 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
949 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
950 // File listing spans multiple containers/shards
951 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
953 return new FileBackendStoreShardDirIterator( $this,
954 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
959 * Do not call this function from places outside FileBackend
961 * @see FileBackendStore::getDirectoryList()
963 * @param string $container Resolved container name
964 * @param string $dir Resolved path relative to container
965 * @param array $params
966 * @return Traversable|array|null Returns null on failure
968 abstract public function getDirectoryListInternal( $container, $dir, array $params );
970 final public function getFileList( array $params ) {
971 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
972 if ( $dir === null ) { // invalid storage path
975 if ( $shard !== null ) {
976 // File listing is confined to a single container/shard
977 return $this->getFileListInternal( $fullCont, $dir, $params );
979 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
980 // File listing spans multiple containers/shards
981 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
983 return new FileBackendStoreShardFileIterator( $this,
984 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
989 * Do not call this function from places outside FileBackend
991 * @see FileBackendStore::getFileList()
993 * @param string $container Resolved container name
994 * @param string $dir Resolved path relative to container
995 * @param array $params
996 * @return Traversable|array|null Returns null on failure
998 abstract public function getFileListInternal( $container, $dir, array $params );
1001 * Return a list of FileOp objects from a list of operations.
1002 * Do not call this function from places outside FileBackend.
1004 * The result must have the same number of items as the input.
1005 * An exception is thrown if an unsupported operation is requested.
1007 * @param array $ops Same format as doOperations()
1008 * @return FileOp[] List of FileOp objects
1009 * @throws FileBackendError
1011 final public function getOperationsInternal( array $ops ) {
1013 'store' => StoreFileOp
::class,
1014 'copy' => CopyFileOp
::class,
1015 'move' => MoveFileOp
::class,
1016 'delete' => DeleteFileOp
::class,
1017 'create' => CreateFileOp
::class,
1018 'describe' => DescribeFileOp
::class,
1019 'null' => NullFileOp
::class
1022 $performOps = []; // array of FileOp objects
1023 // Build up ordered array of FileOps...
1024 foreach ( $ops as $operation ) {
1025 $opName = $operation['op'];
1026 if ( isset( $supportedOps[$opName] ) ) {
1027 $class = $supportedOps[$opName];
1028 // Get params for this operation
1029 $params = $operation;
1030 // Append the FileOp class
1031 $performOps[] = new $class( $this, $params, $this->logger
);
1033 throw new FileBackendError( "Operation '$opName' is not supported." );
1041 * Get a list of storage paths to lock for a list of operations
1042 * Returns an array with LockManager::LOCK_UW (shared locks) and
1043 * LockManager::LOCK_EX (exclusive locks) keys, each corresponding
1044 * to a list of storage paths to be locked. All returned paths are
1047 * @param array $performOps List of FileOp objects
1048 * @return array (LockManager::LOCK_UW => path list, LockManager::LOCK_EX => path list)
1050 final public function getPathsToLockForOpsInternal( array $performOps ) {
1051 // Build up a list of files to lock...
1052 $paths = [ 'sh' => [], 'ex' => [] ];
1053 foreach ( $performOps as $fileOp ) {
1054 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1055 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1057 // Optimization: if doing an EX lock anyway, don't also set an SH one
1058 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1059 // Get a shared lock on the parent directory of each path changed
1060 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1063 LockManager
::LOCK_UW
=> $paths['sh'],
1064 LockManager
::LOCK_EX
=> $paths['ex']
1068 public function getScopedLocksForOps( array $ops, StatusValue
$status ) {
1069 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1071 return $this->getScopedFileLocks( $paths, 'mixed', $status );
1074 final protected function doOperationsInternal( array $ops, array $opts ) {
1075 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1076 $status = $this->newStatus();
1078 // Fix up custom header name/value pairs...
1079 $ops = array_map( [ $this, 'sanitizeOpHeaders' ], $ops );
1081 // Build up a list of FileOps...
1082 $performOps = $this->getOperationsInternal( $ops );
1084 // Acquire any locks as needed...
1085 if ( empty( $opts['nonLocking'] ) ) {
1086 // Build up a list of files to lock...
1087 $paths = $this->getPathsToLockForOpsInternal( $performOps );
1088 // Try to lock those files for the scope of this function...
1090 $scopeLock = $this->getScopedFileLocks( $paths, 'mixed', $status );
1091 if ( !$status->isOK() ) {
1092 return $status; // abort
1096 // Clear any file cache entries (after locks acquired)
1097 if ( empty( $opts['preserveCache'] ) ) {
1098 $this->clearCache();
1101 // Build the list of paths involved
1103 foreach ( $performOps as $performOp ) {
1104 $paths = array_merge( $paths, $performOp->storagePathsRead() );
1105 $paths = array_merge( $paths, $performOp->storagePathsChanged() );
1108 // Enlarge the cache to fit the stat entries of these files
1109 $this->cheapCache
->setMaxSize( max( 2 * count( $paths ), self
::CACHE_CHEAP_SIZE
) );
1111 // Load from the persistent container caches
1112 $this->primeContainerCache( $paths );
1113 // Get the latest stat info for all the files (having locked them)
1114 $ok = $this->preloadFileStat( [ 'srcs' => $paths, 'latest' => true ] );
1117 // Actually attempt the operation batch...
1118 $opts = $this->setConcurrencyFlags( $opts );
1119 $subStatus = FileOpBatch
::attempt( $performOps, $opts, $this->fileJournal
);
1121 // If we could not even stat some files, then bail out...
1122 $subStatus = $this->newStatus( 'backend-fail-internal', $this->name
);
1123 foreach ( $ops as $i => $op ) { // mark each op as failed
1124 $subStatus->success
[$i] = false;
1125 ++
$subStatus->failCount
;
1127 $this->logger
->error( static::class . "-{$this->name} " .
1128 " stat failure; aborted operations: " . FormatJson
::encode( $ops ) );
1131 // Merge errors into StatusValue fields
1132 $status->merge( $subStatus );
1133 $status->success
= $subStatus->success
; // not done in merge()
1135 // Shrink the stat cache back to normal size
1136 $this->cheapCache
->setMaxSize( self
::CACHE_CHEAP_SIZE
);
1141 final protected function doQuickOperationsInternal( array $ops ) {
1142 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1143 $status = $this->newStatus();
1145 // Fix up custom header name/value pairs...
1146 $ops = array_map( [ $this, 'sanitizeOpHeaders' ], $ops );
1148 // Clear any file cache entries
1149 $this->clearCache();
1151 $supportedOps = [ 'create', 'store', 'copy', 'move', 'delete', 'describe', 'null' ];
1152 // Parallel ops may be disabled in config due to dependencies (e.g. needing popen())
1153 $async = ( $this->parallelize
=== 'implicit' && count( $ops ) > 1 );
1154 $maxConcurrency = $this->concurrency
; // throttle
1155 /** @var StatusValue[] $statuses */
1156 $statuses = []; // array of (index => StatusValue)
1157 $fileOpHandles = []; // list of (index => handle) arrays
1158 $curFileOpHandles = []; // current handle batch
1159 // Perform the sync-only ops and build up op handles for the async ops...
1160 foreach ( $ops as $index => $params ) {
1161 if ( !in_array( $params['op'], $supportedOps ) ) {
1162 throw new FileBackendError( "Operation '{$params['op']}' is not supported." );
1164 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1165 $subStatus = $this->$method( [ 'async' => $async ] +
$params );
1166 if ( $subStatus->value
instanceof FileBackendStoreOpHandle
) { // async
1167 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1168 $fileOpHandles[] = $curFileOpHandles; // push this batch
1169 $curFileOpHandles = [];
1171 $curFileOpHandles[$index] = $subStatus->value
; // keep index
1172 } else { // error or completed
1173 $statuses[$index] = $subStatus; // keep index
1176 if ( count( $curFileOpHandles ) ) {
1177 $fileOpHandles[] = $curFileOpHandles; // last batch
1179 // Do all the async ops that can be done concurrently...
1180 foreach ( $fileOpHandles as $fileHandleBatch ) {
1181 $statuses = $statuses +
$this->executeOpHandlesInternal( $fileHandleBatch );
1183 // Marshall and merge all the responses...
1184 foreach ( $statuses as $index => $subStatus ) {
1185 $status->merge( $subStatus );
1186 if ( $subStatus->isOK() ) {
1187 $status->success
[$index] = true;
1188 ++
$status->successCount
;
1190 $status->success
[$index] = false;
1191 ++
$status->failCount
;
1199 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1200 * The resulting StatusValue object fields will correspond
1201 * to the order in which the handles where given.
1203 * @param FileBackendStoreOpHandle[] $fileOpHandles
1204 * @return StatusValue[] Map of StatusValue objects
1205 * @throws FileBackendError
1207 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1208 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1210 foreach ( $fileOpHandles as $fileOpHandle ) {
1211 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle
) ) {
1212 throw new InvalidArgumentException( "Expected FileBackendStoreOpHandle object." );
1213 } elseif ( $fileOpHandle->backend
->getName() !== $this->getName() ) {
1214 throw new InvalidArgumentException( "Expected handle for this file backend." );
1218 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1219 foreach ( $fileOpHandles as $fileOpHandle ) {
1220 $fileOpHandle->closeResources();
1227 * @see FileBackendStore::executeOpHandlesInternal()
1229 * @param FileBackendStoreOpHandle[] $fileOpHandles
1231 * @throws FileBackendError
1232 * @return StatusValue[] List of corresponding StatusValue objects
1234 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1235 if ( count( $fileOpHandles ) ) {
1236 throw new LogicException( "Backend does not support asynchronous operations." );
1243 * Normalize and filter HTTP headers from a file operation
1245 * This normalizes and strips long HTTP headers from a file operation.
1246 * Most headers are just numbers, but some are allowed to be long.
1247 * This function is useful for cleaning up headers and avoiding backend
1248 * specific errors, especially in the middle of batch file operations.
1250 * @param array $op Same format as doOperation()
1253 protected function sanitizeOpHeaders( array $op ) {
1254 static $longs = [ 'content-disposition' ];
1256 if ( isset( $op['headers'] ) ) { // op sets HTTP headers
1258 foreach ( $op['headers'] as $name => $value ) {
1259 $name = strtolower( $name );
1260 $maxHVLen = in_array( $name, $longs ) ? INF
: 255;
1261 if ( strlen( $name ) > 255 ||
strlen( $value ) > $maxHVLen ) {
1262 trigger_error( "Header '$name: $value' is too long." );
1264 $newHeaders[$name] = strlen( $value ) ?
$value : ''; // null/false => ""
1267 $op['headers'] = $newHeaders;
1273 final public function preloadCache( array $paths ) {
1274 $fullConts = []; // full container names
1275 foreach ( $paths as $path ) {
1276 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1277 $fullConts[] = $fullCont;
1279 // Load from the persistent file and container caches
1280 $this->primeContainerCache( $fullConts );
1281 $this->primeFileCache( $paths );
1284 final public function clearCache( array $paths = null ) {
1285 if ( is_array( $paths ) ) {
1286 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1287 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1289 if ( $paths === null ) {
1290 $this->cheapCache
->clear();
1291 $this->expensiveCache
->clear();
1293 foreach ( $paths as $path ) {
1294 $this->cheapCache
->clear( $path );
1295 $this->expensiveCache
->clear( $path );
1298 $this->doClearCache( $paths );
1302 * Clears any additional stat caches for storage paths
1304 * @see FileBackend::clearCache()
1306 * @param array|null $paths Storage paths (optional)
1308 protected function doClearCache( array $paths = null ) {
1311 final public function preloadFileStat( array $params ) {
1312 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1313 $success = true; // no network errors
1315 $params['concurrency'] = ( $this->parallelize
!== 'off' ) ?
$this->concurrency
: 1;
1316 $stats = $this->doGetFileStatMulti( $params );
1317 if ( $stats === null ) {
1318 return true; // not supported
1321 $latest = !empty( $params['latest'] ); // use latest data?
1322 foreach ( $stats as $path => $stat ) {
1323 $path = FileBackend
::normalizeStoragePath( $path );
1324 if ( $path === null ) {
1325 continue; // this shouldn't happen
1327 if ( is_array( $stat ) ) { // file exists
1328 // Strongly consistent backends can automatically set "latest"
1329 $stat['latest'] = $stat['latest'] ??
$latest;
1330 $this->cheapCache
->setField( $path, 'stat', $stat );
1331 $this->setFileCache( $path, $stat ); // update persistent cache
1332 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
1333 $this->cheapCache
->setField( $path, 'sha1',
1334 [ 'hash' => $stat['sha1'], 'latest' => $latest ] );
1336 if ( isset( $stat['xattr'] ) ) { // some backends store headers/metadata
1337 $stat['xattr'] = self
::normalizeXAttributes( $stat['xattr'] );
1338 $this->cheapCache
->setField( $path, 'xattr',
1339 [ 'map' => $stat['xattr'], 'latest' => $latest ] );
1341 } elseif ( $stat === false ) { // file does not exist
1342 $this->cheapCache
->setField( $path, 'stat',
1343 $latest ?
'NOT_EXIST_LATEST' : 'NOT_EXIST' );
1344 $this->cheapCache
->setField( $path, 'xattr',
1345 [ 'map' => false, 'latest' => $latest ] );
1346 $this->cheapCache
->setField( $path, 'sha1',
1347 [ 'hash' => false, 'latest' => $latest ] );
1348 $this->logger
->debug( __METHOD__
. ': File {path} does not exist', [
1351 } else { // an error occurred
1353 $this->logger
->warning( __METHOD__
. ': Could not stat file {path}', [
1363 * Get file stat information (concurrently if possible) for several files
1365 * @see FileBackend::getFileStat()
1367 * @param array $params Parameters include:
1368 * - srcs : list of source storage paths
1369 * - latest : use the latest available data
1370 * @return array|null Map of storage paths to array|bool|null (returns null if not supported)
1373 protected function doGetFileStatMulti( array $params ) {
1374 return null; // not supported
1378 * Is this a key/value store where directories are just virtual?
1379 * Virtual directories exists in so much as files exists that are
1380 * prefixed with the directory path followed by a forward slash.
1384 abstract protected function directoriesAreVirtual();
1387 * Check if a short container name is valid
1389 * This checks for length and illegal characters.
1390 * This may disallow certain characters that can appear
1391 * in the prefix used to make the full container name.
1393 * @param string $container
1396 final protected static function isValidShortContainerName( $container ) {
1397 // Suffixes like '.xxx' (hex shard chars) or '.seg' (file segments)
1398 // might be used by subclasses. Reserve the dot character for sanity.
1399 // The only way dots end up in containers (e.g. resolveStoragePath)
1400 // is due to the wikiId container prefix or the above suffixes.
1401 return self
::isValidContainerName( $container ) && !preg_match( '/[.]/', $container );
1405 * Check if a full container name is valid
1407 * This checks for length and illegal characters.
1408 * Limiting the characters makes migrations to other stores easier.
1410 * @param string $container
1413 final protected static function isValidContainerName( $container ) {
1414 // This accounts for NTFS, Swift, and Ceph restrictions
1415 // and disallows directory separators or traversal characters.
1416 // Note that matching strings URL encode to the same string;
1417 // in Swift/Ceph, the length restriction is *after* URL encoding.
1418 return (bool)preg_match( '/^[a-z0-9][a-z0-9-_.]{0,199}$/i', $container );
1422 * Splits a storage path into an internal container name,
1423 * an internal relative file name, and a container shard suffix.
1424 * Any shard suffix is already appended to the internal container name.
1425 * This also checks that the storage path is valid and within this backend.
1427 * If the container is sharded but a suffix could not be determined,
1428 * this means that the path can only refer to a directory and can only
1429 * be scanned by looking in all the container shards.
1431 * @param string $storagePath
1432 * @return array (container, path, container suffix) or (null, null, null) if invalid
1434 final protected function resolveStoragePath( $storagePath ) {
1435 list( $backend, $shortCont, $relPath ) = self
::splitStoragePath( $storagePath );
1436 if ( $backend === $this->name
) { // must be for this backend
1437 $relPath = self
::normalizeContainerPath( $relPath );
1438 if ( $relPath !== null && self
::isValidShortContainerName( $shortCont ) ) {
1439 // Get shard for the normalized path if this container is sharded
1440 $cShard = $this->getContainerShard( $shortCont, $relPath );
1441 // Validate and sanitize the relative path (backend-specific)
1442 $relPath = $this->resolveContainerPath( $shortCont, $relPath );
1443 if ( $relPath !== null ) {
1444 // Prepend any wiki ID prefix to the container name
1445 $container = $this->fullContainerName( $shortCont );
1446 if ( self
::isValidContainerName( $container ) ) {
1447 // Validate and sanitize the container name (backend-specific)
1448 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1449 if ( $container !== null ) {
1450 return [ $container, $relPath, $cShard ];
1457 return [ null, null, null ];
1461 * Like resolveStoragePath() except null values are returned if
1462 * the container is sharded and the shard could not be determined
1463 * or if the path ends with '/'. The latter case is illegal for FS
1464 * backends and can confuse listings for object store backends.
1466 * This function is used when resolving paths that must be valid
1467 * locations for files. Directory and listing functions should
1468 * generally just use resolveStoragePath() instead.
1470 * @see FileBackendStore::resolveStoragePath()
1472 * @param string $storagePath
1473 * @return array (container, path) or (null, null) if invalid
1475 final protected function resolveStoragePathReal( $storagePath ) {
1476 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1477 if ( $cShard !== null && substr( $relPath, -1 ) !== '/' ) {
1478 return [ $container, $relPath ];
1481 return [ null, null ];
1485 * Get the container name shard suffix for a given path.
1486 * Any empty suffix means the container is not sharded.
1488 * @param string $container Container name
1489 * @param string $relPath Storage path relative to the container
1490 * @return string|null Returns null if shard could not be determined
1492 final protected function getContainerShard( $container, $relPath ) {
1493 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1494 if ( $levels == 1 ||
$levels == 2 ) {
1495 // Hash characters are either base 16 or 36
1496 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1497 // Get a regex that represents the shard portion of paths.
1498 // The concatenation of the captures gives us the shard.
1499 if ( $levels === 1 ) { // 16 or 36 shards per container
1500 $hashDirRegex = '(' . $char . ')';
1501 } else { // 256 or 1296 shards per container
1502 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1503 $hashDirRegex = $char . '/(' . $char . '{2})';
1504 } else { // short hash dir format (e.g. "a/b/c")
1505 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1508 // Allow certain directories to be above the hash dirs so as
1509 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1510 // They must be 2+ chars to avoid any hash directory ambiguity.
1512 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1513 return '.' . implode( '', array_slice( $m, 1 ) );
1516 return null; // failed to match
1519 return ''; // no sharding
1523 * Check if a storage path maps to a single shard.
1524 * Container dirs like "a", where the container shards on "x/xy",
1525 * can reside on several shards. Such paths are tricky to handle.
1527 * @param string $storagePath Storage path
1530 final public function isSingleShardPathInternal( $storagePath ) {
1531 list( , , $shard ) = $this->resolveStoragePath( $storagePath );
1533 return ( $shard !== null );
1537 * Get the sharding config for a container.
1538 * If greater than 0, then all file storage paths within
1539 * the container are required to be hashed accordingly.
1541 * @param string $container
1542 * @return array (integer levels, integer base, repeat flag) or (0, 0, false)
1544 final protected function getContainerHashLevels( $container ) {
1545 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1546 $config = $this->shardViaHashLevels
[$container];
1547 $hashLevels = (int)$config['levels'];
1548 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1549 $hashBase = (int)$config['base'];
1550 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1551 return [ $hashLevels, $hashBase, $config['repeat'] ];
1556 return [ 0, 0, false ]; // no sharding
1560 * Get a list of full container shard suffixes for a container
1562 * @param string $container
1565 final protected function getContainerSuffixes( $container ) {
1567 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1568 if ( $digits > 0 ) {
1569 $numShards = $base ** $digits;
1570 for ( $index = 0; $index < $numShards; $index++
) {
1571 $shards[] = '.' . Wikimedia\base_convert
( $index, 10, $base, $digits );
1579 * Get the full container name, including the wiki ID prefix
1581 * @param string $container
1584 final protected function fullContainerName( $container ) {
1585 if ( $this->domainId
!= '' ) {
1586 return "{$this->domainId}-$container";
1593 * Resolve a container name, checking if it's allowed by the backend.
1594 * This is intended for internal use, such as encoding illegal chars.
1595 * Subclasses can override this to be more restrictive.
1597 * @param string $container
1598 * @return string|null
1600 protected function resolveContainerName( $container ) {
1605 * Resolve a relative storage path, checking if it's allowed by the backend.
1606 * This is intended for internal use, such as encoding illegal chars or perhaps
1607 * getting absolute paths (e.g. FS based backends). Note that the relative path
1608 * may be the empty string (e.g. the path is simply to the container).
1610 * @param string $container Container name
1611 * @param string $relStoragePath Storage path relative to the container
1612 * @return string|null Path or null if not valid
1614 protected function resolveContainerPath( $container, $relStoragePath ) {
1615 return $relStoragePath;
1619 * Get the cache key for a container
1621 * @param string $container Resolved container name
1624 private function containerCacheKey( $container ) {
1625 return "filebackend:{$this->name}:{$this->domainId}:container:{$container}";
1629 * Set the cached info for a container
1631 * @param string $container Resolved container name
1632 * @param array $val Information to cache
1634 final protected function setContainerCache( $container, array $val ) {
1635 $this->memCache
->set( $this->containerCacheKey( $container ), $val, 14 * 86400 );
1639 * Delete the cached info for a container.
1640 * The cache key is salted for a while to prevent race conditions.
1642 * @param string $container Resolved container name
1644 final protected function deleteContainerCache( $container ) {
1645 if ( !$this->memCache
->delete( $this->containerCacheKey( $container ), 300 ) ) {
1646 trigger_error( "Unable to delete stat cache for container $container." );
1651 * Do a batch lookup from cache for container stats for all containers
1652 * used in a list of container names or storage paths objects.
1653 * This loads the persistent cache values into the process cache.
1655 * @param array $items
1657 final protected function primeContainerCache( array $items ) {
1658 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1660 $paths = []; // list of storage paths
1661 $contNames = []; // (cache key => resolved container name)
1662 // Get all the paths/containers from the items...
1663 foreach ( $items as $item ) {
1664 if ( self
::isStoragePath( $item ) ) {
1666 } elseif ( is_string( $item ) ) { // full container name
1667 $contNames[$this->containerCacheKey( $item )] = $item;
1670 // Get all the corresponding cache keys for paths...
1671 foreach ( $paths as $path ) {
1672 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1673 if ( $fullCont !== null ) { // valid path for this backend
1674 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1678 $contInfo = []; // (resolved container name => cache value)
1679 // Get all cache entries for these container cache keys...
1680 $values = $this->memCache
->getMulti( array_keys( $contNames ) );
1681 foreach ( $values as $cacheKey => $val ) {
1682 $contInfo[$contNames[$cacheKey]] = $val;
1685 // Populate the container process cache for the backend...
1686 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1690 * Fill the backend-specific process cache given an array of
1691 * resolved container names and their corresponding cached info.
1692 * Only containers that actually exist should appear in the map.
1694 * @param array $containerInfo Map of resolved container names to cached info
1696 protected function doPrimeContainerCache( array $containerInfo ) {
1700 * Get the cache key for a file path
1702 * @param string $path Normalized storage path
1705 private function fileCacheKey( $path ) {
1706 return "filebackend:{$this->name}:{$this->domainId}:file:" . sha1( $path );
1710 * Set the cached stat info for a file path.
1711 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1712 * salting for the case when a file is created at a path were there was none before.
1714 * @param string $path Storage path
1715 * @param array $val Stat information to cache
1717 final protected function setFileCache( $path, array $val ) {
1718 $path = FileBackend
::normalizeStoragePath( $path );
1719 if ( $path === null ) {
1720 return; // invalid storage path
1722 $mtime = ConvertibleTimestamp
::convert( TS_UNIX
, $val['mtime'] );
1723 $ttl = $this->memCache
->adaptiveTTL( $mtime, 7 * 86400, 300, 0.1 );
1724 $key = $this->fileCacheKey( $path );
1725 // Set the cache unless it is currently salted.
1726 $this->memCache
->set( $key, $val, $ttl );
1730 * Delete the cached stat info for a file path.
1731 * The cache key is salted for a while to prevent race conditions.
1732 * Since negatives (404s) are not cached, this does not need to be called when
1733 * a file is created at a path were there was none before.
1735 * @param string $path Storage path
1737 final protected function deleteFileCache( $path ) {
1738 $path = FileBackend
::normalizeStoragePath( $path );
1739 if ( $path === null ) {
1740 return; // invalid storage path
1742 if ( !$this->memCache
->delete( $this->fileCacheKey( $path ), 300 ) ) {
1743 trigger_error( "Unable to delete stat cache for file $path." );
1748 * Do a batch lookup from cache for file stats for all paths
1749 * used in a list of storage paths or FileOp objects.
1750 * This loads the persistent cache values into the process cache.
1752 * @param array $items List of storage paths
1754 final protected function primeFileCache( array $items ) {
1755 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1757 $paths = []; // list of storage paths
1758 $pathNames = []; // (cache key => storage path)
1759 // Get all the paths/containers from the items...
1760 foreach ( $items as $item ) {
1761 if ( self
::isStoragePath( $item ) ) {
1762 $paths[] = FileBackend
::normalizeStoragePath( $item );
1765 // Get rid of any paths that failed normalization...
1766 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1767 // Get all the corresponding cache keys for paths...
1768 foreach ( $paths as $path ) {
1769 list( , $rel, ) = $this->resolveStoragePath( $path );
1770 if ( $rel !== null ) { // valid path for this backend
1771 $pathNames[$this->fileCacheKey( $path )] = $path;
1774 // Get all cache entries for these file cache keys...
1775 $values = $this->memCache
->getMulti( array_keys( $pathNames ) );
1776 foreach ( $values as $cacheKey => $val ) {
1777 $path = $pathNames[$cacheKey];
1778 if ( is_array( $val ) ) {
1779 $val['latest'] = false; // never completely trust cache
1780 $this->cheapCache
->setField( $path, 'stat', $val );
1781 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1782 $this->cheapCache
->setField( $path, 'sha1',
1783 [ 'hash' => $val['sha1'], 'latest' => false ] );
1785 if ( isset( $val['xattr'] ) ) { // some backends store headers/metadata
1786 $val['xattr'] = self
::normalizeXAttributes( $val['xattr'] );
1787 $this->cheapCache
->setField( $path, 'xattr',
1788 [ 'map' => $val['xattr'], 'latest' => false ] );
1795 * Normalize file headers/metadata to the FileBackend::getFileXAttributes() format
1797 * @param array $xattr
1801 final protected static function normalizeXAttributes( array $xattr ) {
1802 $newXAttr = [ 'headers' => [], 'metadata' => [] ];
1804 foreach ( $xattr['headers'] as $name => $value ) {
1805 $newXAttr['headers'][strtolower( $name )] = $value;
1808 foreach ( $xattr['metadata'] as $name => $value ) {
1809 $newXAttr['metadata'][strtolower( $name )] = $value;
1816 * Set the 'concurrency' option from a list of operation options
1818 * @param array $opts Map of operation options
1821 final protected function setConcurrencyFlags( array $opts ) {
1822 $opts['concurrency'] = 1; // off
1823 if ( $this->parallelize
=== 'implicit' ) {
1824 if ( !isset( $opts['parallelize'] ) ||
$opts['parallelize'] ) {
1825 $opts['concurrency'] = $this->concurrency
;
1827 } elseif ( $this->parallelize
=== 'explicit' ) {
1828 if ( !empty( $opts['parallelize'] ) ) {
1829 $opts['concurrency'] = $this->concurrency
;
1837 * Get the content type to use in HEAD/GET requests for a file
1839 * @param string $storagePath
1840 * @param string|null $content File data
1841 * @param string|null $fsPath File system path
1842 * @return string MIME type
1844 protected function getContentType( $storagePath, $content, $fsPath ) {
1845 if ( $this->mimeCallback
) {
1846 return call_user_func_array( $this->mimeCallback
, func_get_args() );
1849 $mime = ( $fsPath !== null ) ?
mime_content_type( $fsPath ) : false;
1850 return $mime ?
: 'unknown/unknown';
1855 * FileBackendStore helper class for performing asynchronous file operations.
1857 * For example, calling FileBackendStore::createInternal() with the "async"
1858 * param flag may result in a StatusValue that contains this object as a value.
1859 * This class is largely backend-specific and is mostly just "magic" to be
1860 * passed to FileBackendStore::executeOpHandlesInternal().
1862 abstract class FileBackendStoreOpHandle
{
1864 public $params = []; // params to caller functions
1865 /** @var FileBackendStore */
1868 public $resourcesToClose = [];
1870 public $call; // string; name that identifies the function called
1873 * Close all open file handles
1875 public function closeResources() {
1876 array_map( 'fclose', $this->resourcesToClose
);
1881 * FileBackendStore helper function to handle listings that span container shards.
1882 * Do not use this class from places outside of FileBackendStore.
1884 * @ingroup FileBackend
1886 abstract class FileBackendStoreShardListIterator
extends FilterIterator
{
1887 /** @var FileBackendStore */
1893 /** @var string Full container name */
1894 protected $container;
1896 /** @var string Resolved relative path */
1897 protected $directory;
1900 protected $multiShardPaths = []; // (rel path => 1)
1903 * @param FileBackendStore $backend
1904 * @param string $container Full storage container name
1905 * @param string $dir Storage directory relative to container
1906 * @param array $suffixes List of container shard suffixes
1907 * @param array $params
1909 public function __construct(
1910 FileBackendStore
$backend, $container, $dir, array $suffixes, array $params
1912 $this->backend
= $backend;
1913 $this->container
= $container;
1914 $this->directory
= $dir;
1915 $this->params
= $params;
1917 $iter = new AppendIterator();
1918 foreach ( $suffixes as $suffix ) {
1919 $iter->append( $this->listFromShard( $this->container
. $suffix ) );
1922 parent
::__construct( $iter );
1925 public function accept() {
1926 $rel = $this->getInnerIterator()->current(); // path relative to given directory
1927 $path = $this->params
['dir'] . "/{$rel}"; // full storage path
1928 if ( $this->backend
->isSingleShardPathInternal( $path ) ) {
1929 return true; // path is only on one shard; no issue with duplicates
1930 } elseif ( isset( $this->multiShardPaths
[$rel] ) ) {
1931 // Don't keep listing paths that are on multiple shards
1934 $this->multiShardPaths
[$rel] = 1;
1940 public function rewind() {
1942 $this->multiShardPaths
= [];
1946 * Get the list for a given container shard
1948 * @param string $container Resolved container name
1951 abstract protected function listFromShard( $container );
1955 * Iterator for listing directories
1957 class FileBackendStoreShardDirIterator
extends FileBackendStoreShardListIterator
{
1958 protected function listFromShard( $container ) {
1959 $list = $this->backend
->getDirectoryListInternal(
1960 $container, $this->directory
, $this->params
);
1961 if ( $list === null ) {
1962 return new ArrayIterator( [] );
1964 return is_array( $list ) ?
new ArrayIterator( $list ) : $list;
1970 * Iterator for listing regular files
1972 class FileBackendStoreShardFileIterator
extends FileBackendStoreShardListIterator
{
1973 protected function listFromShard( $container ) {
1974 $list = $this->backend
->getFileListInternal(
1975 $container, $this->directory
, $this->params
);
1976 if ( $list === null ) {
1977 return new ArrayIterator( [] );
1979 return is_array( $list ) ?
new ArrayIterator( $list ) : $list;