Update docs/hooks.txt for ShowSearchHitTitle
[mediawiki.git] / includes / libs / filebackend / FileBackendStore.php
bloba7ceab2ed514606041714a923e657c4b55bb5da8
1 <?php
2 /**
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
20 * @file
21 * @ingroup FileBackend
22 * @author Aaron Schulz
25 /**
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
36 * @since 1.19
38 abstract class FileBackendStore extends FileBackend {
39 /** @var WANObjectCache */
40 protected $memCache;
41 /** @var BagOStuff */
42 protected $srvCache;
43 /** @var ProcessCacheLRU Map of paths to small (RAM/disk) cache items */
44 protected $cheapCache;
45 /** @var ProcessCacheLRU 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"
60 /**
61 * @see FileBackend::__construct()
62 * Additional $config params include:
63 * - srvCache : BagOStuff cache to APC/XCache 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 = isset( $config['mimeCallback'] )
74 ? $config['mimeCallback']
75 : null;
76 $this->srvCache = new EmptyBagOStuff(); // disabled by default
77 $this->memCache = WANObjectCache::newEmpty(); // disabled by default
78 $this->cheapCache = new ProcessCacheLRU( self::CACHE_CHEAP_SIZE );
79 $this->expensiveCache = new ProcessCacheLRU( self::CACHE_EXPENSIVE_SIZE );
82 /**
83 * Get the maximum allowable file size given backend
84 * medium restrictions and basic performance constraints.
85 * Do not call this function from places outside FileBackend and FileOp.
87 * @return int Bytes
89 final public function maxFileSizeInternal() {
90 return $this->maxFileSize;
93 /**
94 * Check if a file can be created or changed at a given storage path.
95 * FS backends should check if the parent directory exists, files can be
96 * written under it, and that any file already there is writable.
97 * Backends using key/value stores should check if the container exists.
99 * @param string $storagePath
100 * @return bool
102 abstract public function isPathUsableInternal( $storagePath );
105 * Create a file in the backend with the given contents.
106 * This will overwrite any file that exists at the destination.
107 * Do not call this function from places outside FileBackend and FileOp.
109 * $params include:
110 * - content : the raw file contents
111 * - dst : destination storage path
112 * - headers : HTTP header name/value map
113 * - async : StatusValue will be returned immediately if supported.
114 * If the StatusValue is OK, then its value field will be
115 * set to a FileBackendStoreOpHandle object.
116 * - dstExists : Whether a file exists at the destination (optimization).
117 * Callers can use "false" if no existing file is being changed.
119 * @param array $params
120 * @return StatusValue
122 final public function createInternal( array $params ) {
123 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
124 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
125 $status = $this->newStatus( 'backend-fail-maxsize',
126 $params['dst'], $this->maxFileSizeInternal() );
127 } else {
128 $status = $this->doCreateInternal( $params );
129 $this->clearCache( [ $params['dst'] ] );
130 if ( !isset( $params['dstExists'] ) || $params['dstExists'] ) {
131 $this->deleteFileCache( $params['dst'] ); // persistent cache
135 return $status;
139 * @see FileBackendStore::createInternal()
140 * @param array $params
141 * @return StatusValue
143 abstract protected function doCreateInternal( array $params );
146 * Store a file into the backend from a file on disk.
147 * This will overwrite any file that exists at the destination.
148 * Do not call this function from places outside FileBackend and FileOp.
150 * $params include:
151 * - src : source path on disk
152 * - dst : destination storage path
153 * - headers : HTTP header name/value map
154 * - async : StatusValue will be returned immediately if supported.
155 * If the StatusValue is OK, then its value field will be
156 * set to a FileBackendStoreOpHandle object.
157 * - dstExists : Whether a file exists at the destination (optimization).
158 * Callers can use "false" if no existing file is being changed.
160 * @param array $params
161 * @return StatusValue
163 final public function storeInternal( array $params ) {
164 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
165 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
166 $status = $this->newStatus( 'backend-fail-maxsize',
167 $params['dst'], $this->maxFileSizeInternal() );
168 } else {
169 $status = $this->doStoreInternal( $params );
170 $this->clearCache( [ $params['dst'] ] );
171 if ( !isset( $params['dstExists'] ) || $params['dstExists'] ) {
172 $this->deleteFileCache( $params['dst'] ); // persistent cache
176 return $status;
180 * @see FileBackendStore::storeInternal()
181 * @param array $params
182 * @return StatusValue
184 abstract protected function doStoreInternal( array $params );
187 * Copy a file from one storage path to another in the backend.
188 * This will overwrite any file that exists at the destination.
189 * Do not call this function from places outside FileBackend and FileOp.
191 * $params include:
192 * - src : source storage path
193 * - dst : destination storage path
194 * - ignoreMissingSource : do nothing if the source file does not exist
195 * - headers : HTTP header name/value map
196 * - async : StatusValue will be returned immediately if supported.
197 * If the StatusValue is OK, then its value field will be
198 * set to a FileBackendStoreOpHandle object.
199 * - dstExists : Whether a file exists at the destination (optimization).
200 * Callers can use "false" if no existing file is being changed.
202 * @param array $params
203 * @return StatusValue
205 final public function copyInternal( array $params ) {
206 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
207 $status = $this->doCopyInternal( $params );
208 $this->clearCache( [ $params['dst'] ] );
209 if ( !isset( $params['dstExists'] ) || $params['dstExists'] ) {
210 $this->deleteFileCache( $params['dst'] ); // persistent cache
213 return $status;
217 * @see FileBackendStore::copyInternal()
218 * @param array $params
219 * @return StatusValue
221 abstract protected function doCopyInternal( array $params );
224 * Delete a file at the storage path.
225 * Do not call this function from places outside FileBackend and FileOp.
227 * $params include:
228 * - src : source storage path
229 * - ignoreMissingSource : do nothing if the source file does not exist
230 * - async : StatusValue will be returned immediately if supported.
231 * If the StatusValue is OK, then its value field will be
232 * set to a FileBackendStoreOpHandle object.
234 * @param array $params
235 * @return StatusValue
237 final public function deleteInternal( array $params ) {
238 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
239 $status = $this->doDeleteInternal( $params );
240 $this->clearCache( [ $params['src'] ] );
241 $this->deleteFileCache( $params['src'] ); // persistent cache
242 return $status;
246 * @see FileBackendStore::deleteInternal()
247 * @param array $params
248 * @return StatusValue
250 abstract protected function doDeleteInternal( array $params );
253 * Move a file from one storage path to another in the backend.
254 * This will overwrite any file that exists at the destination.
255 * Do not call this function from places outside FileBackend and FileOp.
257 * $params include:
258 * - src : source storage path
259 * - dst : destination storage path
260 * - ignoreMissingSource : do nothing if the source file does not exist
261 * - headers : HTTP header name/value map
262 * - async : StatusValue will be returned immediately if supported.
263 * If the StatusValue is OK, then its value field will be
264 * set to a FileBackendStoreOpHandle object.
265 * - dstExists : Whether a file exists at the destination (optimization).
266 * Callers can use "false" if no existing file is being changed.
268 * @param array $params
269 * @return StatusValue
271 final public function moveInternal( array $params ) {
272 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
273 $status = $this->doMoveInternal( $params );
274 $this->clearCache( [ $params['src'], $params['dst'] ] );
275 $this->deleteFileCache( $params['src'] ); // persistent cache
276 if ( !isset( $params['dstExists'] ) || $params['dstExists'] ) {
277 $this->deleteFileCache( $params['dst'] ); // persistent cache
280 return $status;
284 * @see FileBackendStore::moveInternal()
285 * @param array $params
286 * @return StatusValue
288 protected function doMoveInternal( array $params ) {
289 unset( $params['async'] ); // two steps, won't work here :)
290 $nsrc = FileBackend::normalizeStoragePath( $params['src'] );
291 $ndst = FileBackend::normalizeStoragePath( $params['dst'] );
292 // Copy source to dest
293 $status = $this->copyInternal( $params );
294 if ( $nsrc !== $ndst && $status->isOK() ) {
295 // Delete source (only fails due to races or network problems)
296 $status->merge( $this->deleteInternal( [ 'src' => $params['src'] ] ) );
297 $status->setResult( true, $status->value ); // ignore delete() errors
300 return $status;
304 * Alter metadata for a file at the storage path.
305 * Do not call this function from places outside FileBackend and FileOp.
307 * $params include:
308 * - src : source storage path
309 * - headers : HTTP header name/value map
310 * - async : StatusValue will be returned immediately if supported.
311 * If the StatusValue is OK, then its value field will be
312 * set to a FileBackendStoreOpHandle object.
314 * @param array $params
315 * @return StatusValue
317 final public function describeInternal( array $params ) {
318 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
319 if ( count( $params['headers'] ) ) {
320 $status = $this->doDescribeInternal( $params );
321 $this->clearCache( [ $params['src'] ] );
322 $this->deleteFileCache( $params['src'] ); // persistent cache
323 } else {
324 $status = $this->newStatus(); // nothing to do
327 return $status;
331 * @see FileBackendStore::describeInternal()
332 * @param array $params
333 * @return StatusValue
335 protected function doDescribeInternal( array $params ) {
336 return $this->newStatus();
340 * No-op file operation that does nothing.
341 * Do not call this function from places outside FileBackend and FileOp.
343 * @param array $params
344 * @return StatusValue
346 final public function nullInternal( array $params ) {
347 return $this->newStatus();
350 final public function concatenate( array $params ) {
351 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
352 $status = $this->newStatus();
354 // Try to lock the source files for the scope of this function
355 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager::LOCK_UW, $status );
356 if ( $status->isOK() ) {
357 // Actually do the file concatenation...
358 $start_time = microtime( true );
359 $status->merge( $this->doConcatenate( $params ) );
360 $sec = microtime( true ) - $start_time;
361 if ( !$status->isOK() ) {
362 $this->logger->error( get_class( $this ) . "-{$this->name}" .
363 " failed to concatenate " . count( $params['srcs'] ) . " file(s) [$sec sec]" );
367 return $status;
371 * @see FileBackendStore::concatenate()
372 * @param array $params
373 * @return StatusValue
375 protected function doConcatenate( array $params ) {
376 $status = $this->newStatus();
377 $tmpPath = $params['dst']; // convenience
378 unset( $params['latest'] ); // sanity
380 // Check that the specified temp file is valid...
381 MediaWiki\suppressWarnings();
382 $ok = ( is_file( $tmpPath ) && filesize( $tmpPath ) == 0 );
383 MediaWiki\restoreWarnings();
384 if ( !$ok ) { // not present or not empty
385 $status->fatal( 'backend-fail-opentemp', $tmpPath );
387 return $status;
390 // Get local FS versions of the chunks needed for the concatenation...
391 $fsFiles = $this->getLocalReferenceMulti( $params );
392 foreach ( $fsFiles as $path => &$fsFile ) {
393 if ( !$fsFile ) { // chunk failed to download?
394 $fsFile = $this->getLocalReference( [ 'src' => $path ] );
395 if ( !$fsFile ) { // retry failed?
396 $status->fatal( 'backend-fail-read', $path );
398 return $status;
402 unset( $fsFile ); // unset reference so we can reuse $fsFile
404 // Get a handle for the destination temp file
405 $tmpHandle = fopen( $tmpPath, 'ab' );
406 if ( $tmpHandle === false ) {
407 $status->fatal( 'backend-fail-opentemp', $tmpPath );
409 return $status;
412 // Build up the temp file using the source chunks (in order)...
413 foreach ( $fsFiles as $virtualSource => $fsFile ) {
414 // Get a handle to the local FS version
415 $sourceHandle = fopen( $fsFile->getPath(), 'rb' );
416 if ( $sourceHandle === false ) {
417 fclose( $tmpHandle );
418 $status->fatal( 'backend-fail-read', $virtualSource );
420 return $status;
422 // Append chunk to file (pass chunk size to avoid magic quotes)
423 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
424 fclose( $sourceHandle );
425 fclose( $tmpHandle );
426 $status->fatal( 'backend-fail-writetemp', $tmpPath );
428 return $status;
430 fclose( $sourceHandle );
432 if ( !fclose( $tmpHandle ) ) {
433 $status->fatal( 'backend-fail-closetemp', $tmpPath );
435 return $status;
438 clearstatcache(); // temp file changed
440 return $status;
443 final protected function doPrepare( array $params ) {
444 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
445 $status = $this->newStatus();
447 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
448 if ( $dir === null ) {
449 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
451 return $status; // invalid storage path
454 if ( $shard !== null ) { // confined to a single container/shard
455 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
456 } else { // directory is on several shards
457 $this->logger->debug( __METHOD__ . ": iterating over all container shards.\n" );
458 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
459 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
460 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
464 return $status;
468 * @see FileBackendStore::doPrepare()
469 * @param string $container
470 * @param string $dir
471 * @param array $params
472 * @return StatusValue
474 protected function doPrepareInternal( $container, $dir, array $params ) {
475 return $this->newStatus();
478 final protected function doSecure( array $params ) {
479 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
480 $status = $this->newStatus();
482 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
483 if ( $dir === null ) {
484 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
486 return $status; // invalid storage path
489 if ( $shard !== null ) { // confined to a single container/shard
490 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
491 } else { // directory is on several shards
492 $this->logger->debug( __METHOD__ . ": iterating over all container shards.\n" );
493 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
494 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
495 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
499 return $status;
503 * @see FileBackendStore::doSecure()
504 * @param string $container
505 * @param string $dir
506 * @param array $params
507 * @return StatusValue
509 protected function doSecureInternal( $container, $dir, array $params ) {
510 return $this->newStatus();
513 final protected function doPublish( array $params ) {
514 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
515 $status = $this->newStatus();
517 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
518 if ( $dir === null ) {
519 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
521 return $status; // invalid storage path
524 if ( $shard !== null ) { // confined to a single container/shard
525 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
526 } else { // directory is on several shards
527 $this->logger->debug( __METHOD__ . ": iterating over all container shards.\n" );
528 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
529 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
530 $status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
534 return $status;
538 * @see FileBackendStore::doPublish()
539 * @param string $container
540 * @param string $dir
541 * @param array $params
542 * @return StatusValue
544 protected function doPublishInternal( $container, $dir, array $params ) {
545 return $this->newStatus();
548 final protected function doClean( array $params ) {
549 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
550 $status = $this->newStatus();
552 // Recursive: first delete all empty subdirs recursively
553 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
554 $subDirsRel = $this->getTopDirectoryList( [ 'dir' => $params['dir'] ] );
555 if ( $subDirsRel !== null ) { // no errors
556 foreach ( $subDirsRel as $subDirRel ) {
557 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
558 $status->merge( $this->doClean( [ 'dir' => $subDir ] + $params ) );
560 unset( $subDirsRel ); // free directory for rmdir() on Windows (for FS backends)
564 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
565 if ( $dir === null ) {
566 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
568 return $status; // invalid storage path
571 // Attempt to lock this directory...
572 $filesLockEx = [ $params['dir'] ];
573 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager::LOCK_EX, $status );
574 if ( !$status->isOK() ) {
575 return $status; // abort
578 if ( $shard !== null ) { // confined to a single container/shard
579 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
580 $this->deleteContainerCache( $fullCont ); // purge cache
581 } else { // directory is on several shards
582 $this->logger->debug( __METHOD__ . ": iterating over all container shards.\n" );
583 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
584 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
585 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
586 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
590 return $status;
594 * @see FileBackendStore::doClean()
595 * @param string $container
596 * @param string $dir
597 * @param array $params
598 * @return StatusValue
600 protected function doCleanInternal( $container, $dir, array $params ) {
601 return $this->newStatus();
604 final public function fileExists( array $params ) {
605 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
606 $stat = $this->getFileStat( $params );
608 return ( $stat === null ) ? null : (bool)$stat; // null => failure
611 final public function getFileTimestamp( array $params ) {
612 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
613 $stat = $this->getFileStat( $params );
615 return $stat ? $stat['mtime'] : false;
618 final public function getFileSize( array $params ) {
619 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
620 $stat = $this->getFileStat( $params );
622 return $stat ? $stat['size'] : false;
625 final public function getFileStat( array $params ) {
626 $path = self::normalizeStoragePath( $params['src'] );
627 if ( $path === null ) {
628 return false; // invalid storage path
630 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
631 $latest = !empty( $params['latest'] ); // use latest data?
632 if ( !$latest && !$this->cheapCache->has( $path, 'stat', self::CACHE_TTL ) ) {
633 $this->primeFileCache( [ $path ] ); // check persistent cache
635 if ( $this->cheapCache->has( $path, 'stat', self::CACHE_TTL ) ) {
636 $stat = $this->cheapCache->get( $path, 'stat' );
637 // If we want the latest data, check that this cached
638 // value was in fact fetched with the latest available data.
639 if ( is_array( $stat ) ) {
640 if ( !$latest || $stat['latest'] ) {
641 return $stat;
643 } elseif ( in_array( $stat, [ 'NOT_EXIST', 'NOT_EXIST_LATEST' ] ) ) {
644 if ( !$latest || $stat === 'NOT_EXIST_LATEST' ) {
645 return false;
649 $stat = $this->doGetFileStat( $params );
650 if ( is_array( $stat ) ) { // file exists
651 // Strongly consistent backends can automatically set "latest"
652 $stat['latest'] = isset( $stat['latest'] ) ? $stat['latest'] : $latest;
653 $this->cheapCache->set( $path, 'stat', $stat );
654 $this->setFileCache( $path, $stat ); // update persistent cache
655 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
656 $this->cheapCache->set( $path, 'sha1',
657 [ 'hash' => $stat['sha1'], 'latest' => $latest ] );
659 if ( isset( $stat['xattr'] ) ) { // some backends store headers/metadata
660 $stat['xattr'] = self::normalizeXAttributes( $stat['xattr'] );
661 $this->cheapCache->set( $path, 'xattr',
662 [ 'map' => $stat['xattr'], 'latest' => $latest ] );
664 } elseif ( $stat === false ) { // file does not exist
665 $this->cheapCache->set( $path, 'stat', $latest ? 'NOT_EXIST_LATEST' : 'NOT_EXIST' );
666 $this->cheapCache->set( $path, 'xattr', [ 'map' => false, 'latest' => $latest ] );
667 $this->cheapCache->set( $path, 'sha1', [ 'hash' => false, 'latest' => $latest ] );
668 $this->logger->debug( __METHOD__ . ": File $path does not exist.\n" );
669 } else { // an error occurred
670 $this->logger->warning( __METHOD__ . ": Could not stat file $path.\n" );
673 return $stat;
677 * @see FileBackendStore::getFileStat()
678 * @param array $params
680 abstract protected function doGetFileStat( array $params );
682 public function getFileContentsMulti( array $params ) {
683 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
685 $params = $this->setConcurrencyFlags( $params );
686 $contents = $this->doGetFileContentsMulti( $params );
688 return $contents;
692 * @see FileBackendStore::getFileContentsMulti()
693 * @param array $params
694 * @return array
696 protected function doGetFileContentsMulti( array $params ) {
697 $contents = [];
698 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
699 MediaWiki\suppressWarnings();
700 $contents[$path] = $fsFile ? file_get_contents( $fsFile->getPath() ) : false;
701 MediaWiki\restoreWarnings();
704 return $contents;
707 final public function getFileXAttributes( array $params ) {
708 $path = self::normalizeStoragePath( $params['src'] );
709 if ( $path === null ) {
710 return false; // invalid storage path
712 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
713 $latest = !empty( $params['latest'] ); // use latest data?
714 if ( $this->cheapCache->has( $path, 'xattr', self::CACHE_TTL ) ) {
715 $stat = $this->cheapCache->get( $path, 'xattr' );
716 // If we want the latest data, check that this cached
717 // value was in fact fetched with the latest available data.
718 if ( !$latest || $stat['latest'] ) {
719 return $stat['map'];
722 $fields = $this->doGetFileXAttributes( $params );
723 $fields = is_array( $fields ) ? self::normalizeXAttributes( $fields ) : false;
724 $this->cheapCache->set( $path, 'xattr', [ 'map' => $fields, 'latest' => $latest ] );
726 return $fields;
730 * @see FileBackendStore::getFileXAttributes()
731 * @param array $params
732 * @return array[][]
734 protected function doGetFileXAttributes( array $params ) {
735 return [ 'headers' => [], 'metadata' => [] ]; // not supported
738 final public function getFileSha1Base36( array $params ) {
739 $path = self::normalizeStoragePath( $params['src'] );
740 if ( $path === null ) {
741 return false; // invalid storage path
743 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
744 $latest = !empty( $params['latest'] ); // use latest data?
745 if ( $this->cheapCache->has( $path, 'sha1', self::CACHE_TTL ) ) {
746 $stat = $this->cheapCache->get( $path, 'sha1' );
747 // If we want the latest data, check that this cached
748 // value was in fact fetched with the latest available data.
749 if ( !$latest || $stat['latest'] ) {
750 return $stat['hash'];
753 $hash = $this->doGetFileSha1Base36( $params );
754 $this->cheapCache->set( $path, 'sha1', [ 'hash' => $hash, 'latest' => $latest ] );
756 return $hash;
760 * @see FileBackendStore::getFileSha1Base36()
761 * @param array $params
762 * @return bool|string
764 protected function doGetFileSha1Base36( array $params ) {
765 $fsFile = $this->getLocalReference( $params );
766 if ( !$fsFile ) {
767 return false;
768 } else {
769 return $fsFile->getSha1Base36();
773 final public function getFileProps( array $params ) {
774 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
775 $fsFile = $this->getLocalReference( $params );
776 $props = $fsFile ? $fsFile->getProps() : FSFile::placeholderProps();
778 return $props;
781 final public function getLocalReferenceMulti( array $params ) {
782 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
784 $params = $this->setConcurrencyFlags( $params );
786 $fsFiles = []; // (path => FSFile)
787 $latest = !empty( $params['latest'] ); // use latest data?
788 // Reuse any files already in process cache...
789 foreach ( $params['srcs'] as $src ) {
790 $path = self::normalizeStoragePath( $src );
791 if ( $path === null ) {
792 $fsFiles[$src] = null; // invalid storage path
793 } elseif ( $this->expensiveCache->has( $path, 'localRef' ) ) {
794 $val = $this->expensiveCache->get( $path, 'localRef' );
795 // If we want the latest data, check that this cached
796 // value was in fact fetched with the latest available data.
797 if ( !$latest || $val['latest'] ) {
798 $fsFiles[$src] = $val['object'];
802 // Fetch local references of any remaning files...
803 $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
804 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
805 $fsFiles[$path] = $fsFile;
806 if ( $fsFile ) { // update the process cache...
807 $this->expensiveCache->set( $path, 'localRef',
808 [ 'object' => $fsFile, 'latest' => $latest ] );
812 return $fsFiles;
816 * @see FileBackendStore::getLocalReferenceMulti()
817 * @param array $params
818 * @return array
820 protected function doGetLocalReferenceMulti( array $params ) {
821 return $this->doGetLocalCopyMulti( $params );
824 final public function getLocalCopyMulti( array $params ) {
825 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
827 $params = $this->setConcurrencyFlags( $params );
828 $tmpFiles = $this->doGetLocalCopyMulti( $params );
830 return $tmpFiles;
834 * @see FileBackendStore::getLocalCopyMulti()
835 * @param array $params
836 * @return array
838 abstract protected function doGetLocalCopyMulti( array $params );
841 * @see FileBackend::getFileHttpUrl()
842 * @param array $params
843 * @return string|null
845 public function getFileHttpUrl( array $params ) {
846 return null; // not supported
849 final public function streamFile( array $params ) {
850 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
851 $status = $this->newStatus();
853 // Always set some fields for subclass convenience
854 $params['options'] = isset( $params['options'] ) ? $params['options'] : [];
855 $params['headers'] = isset( $params['headers'] ) ? $params['headers'] : [];
857 // Don't stream it out as text/html if there was a PHP error
858 if ( ( empty( $params['headless'] ) || $params['headers'] ) && headers_sent() ) {
859 print "Headers already sent, terminating.\n";
860 $status->fatal( 'backend-fail-stream', $params['src'] );
861 return $status;
864 $status->merge( $this->doStreamFile( $params ) );
866 return $status;
870 * @see FileBackendStore::streamFile()
871 * @param array $params
872 * @return StatusValue
874 protected function doStreamFile( array $params ) {
875 $status = $this->newStatus();
877 $flags = 0;
878 $flags |= !empty( $params['headless'] ) ? HTTPFileStreamer::STREAM_HEADLESS : 0;
879 $flags |= !empty( $params['allowOB'] ) ? HTTPFileStreamer::STREAM_ALLOW_OB : 0;
881 $fsFile = $this->getLocalReference( $params );
882 if ( $fsFile ) {
883 $streamer = new HTTPFileStreamer(
884 $fsFile->getPath(),
886 'obResetFunc' => $this->obResetFunc,
887 'streamMimeFunc' => $this->streamMimeFunc
890 $res = $streamer->stream( $params['headers'], true, $params['options'], $flags );
891 } else {
892 $res = false;
893 HTTPFileStreamer::send404Message( $params['src'], $flags );
896 if ( !$res ) {
897 $status->fatal( 'backend-fail-stream', $params['src'] );
900 return $status;
903 final public function directoryExists( array $params ) {
904 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
905 if ( $dir === null ) {
906 return false; // invalid storage path
908 if ( $shard !== null ) { // confined to a single container/shard
909 return $this->doDirectoryExists( $fullCont, $dir, $params );
910 } else { // directory is on several shards
911 $this->logger->debug( __METHOD__ . ": iterating over all container shards.\n" );
912 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
913 $res = false; // response
914 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
915 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
916 if ( $exists ) {
917 $res = true;
918 break; // found one!
919 } elseif ( $exists === null ) { // error?
920 $res = null; // if we don't find anything, it is indeterminate
924 return $res;
929 * @see FileBackendStore::directoryExists()
931 * @param string $container Resolved container name
932 * @param string $dir Resolved path relative to container
933 * @param array $params
934 * @return bool|null
936 abstract protected function doDirectoryExists( $container, $dir, array $params );
938 final public function getDirectoryList( array $params ) {
939 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
940 if ( $dir === null ) { // invalid storage path
941 return null;
943 if ( $shard !== null ) {
944 // File listing is confined to a single container/shard
945 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
946 } else {
947 $this->logger->debug( __METHOD__ . ": iterating over all container shards.\n" );
948 // File listing spans multiple containers/shards
949 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
951 return new FileBackendStoreShardDirIterator( $this,
952 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
957 * Do not call this function from places outside FileBackend
959 * @see FileBackendStore::getDirectoryList()
961 * @param string $container Resolved container name
962 * @param string $dir Resolved path relative to container
963 * @param array $params
964 * @return Traversable|array|null Returns null on failure
966 abstract public function getDirectoryListInternal( $container, $dir, array $params );
968 final public function getFileList( array $params ) {
969 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
970 if ( $dir === null ) { // invalid storage path
971 return null;
973 if ( $shard !== null ) {
974 // File listing is confined to a single container/shard
975 return $this->getFileListInternal( $fullCont, $dir, $params );
976 } else {
977 $this->logger->debug( __METHOD__ . ": iterating over all container shards.\n" );
978 // File listing spans multiple containers/shards
979 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
981 return new FileBackendStoreShardFileIterator( $this,
982 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
987 * Do not call this function from places outside FileBackend
989 * @see FileBackendStore::getFileList()
991 * @param string $container Resolved container name
992 * @param string $dir Resolved path relative to container
993 * @param array $params
994 * @return Traversable|array|null Returns null on failure
996 abstract public function getFileListInternal( $container, $dir, array $params );
999 * Return a list of FileOp objects from a list of operations.
1000 * Do not call this function from places outside FileBackend.
1002 * The result must have the same number of items as the input.
1003 * An exception is thrown if an unsupported operation is requested.
1005 * @param array $ops Same format as doOperations()
1006 * @return FileOp[] List of FileOp objects
1007 * @throws FileBackendError
1009 final public function getOperationsInternal( array $ops ) {
1010 $supportedOps = [
1011 'store' => 'StoreFileOp',
1012 'copy' => 'CopyFileOp',
1013 'move' => 'MoveFileOp',
1014 'delete' => 'DeleteFileOp',
1015 'create' => 'CreateFileOp',
1016 'describe' => 'DescribeFileOp',
1017 'null' => 'NullFileOp'
1020 $performOps = []; // array of FileOp objects
1021 // Build up ordered array of FileOps...
1022 foreach ( $ops as $operation ) {
1023 $opName = $operation['op'];
1024 if ( isset( $supportedOps[$opName] ) ) {
1025 $class = $supportedOps[$opName];
1026 // Get params for this operation
1027 $params = $operation;
1028 // Append the FileOp class
1029 $performOps[] = new $class( $this, $params, $this->logger );
1030 } else {
1031 throw new FileBackendError( "Operation '$opName' is not supported." );
1035 return $performOps;
1039 * Get a list of storage paths to lock for a list of operations
1040 * Returns an array with LockManager::LOCK_UW (shared locks) and
1041 * LockManager::LOCK_EX (exclusive locks) keys, each corresponding
1042 * to a list of storage paths to be locked. All returned paths are
1043 * normalized.
1045 * @param array $performOps List of FileOp objects
1046 * @return array (LockManager::LOCK_UW => path list, LockManager::LOCK_EX => path list)
1048 final public function getPathsToLockForOpsInternal( array $performOps ) {
1049 // Build up a list of files to lock...
1050 $paths = [ 'sh' => [], 'ex' => [] ];
1051 foreach ( $performOps as $fileOp ) {
1052 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1053 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1055 // Optimization: if doing an EX lock anyway, don't also set an SH one
1056 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1057 // Get a shared lock on the parent directory of each path changed
1058 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1060 return [
1061 LockManager::LOCK_UW => $paths['sh'],
1062 LockManager::LOCK_EX => $paths['ex']
1066 public function getScopedLocksForOps( array $ops, StatusValue $status ) {
1067 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1069 return $this->getScopedFileLocks( $paths, 'mixed', $status );
1072 final protected function doOperationsInternal( array $ops, array $opts ) {
1073 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1074 $status = $this->newStatus();
1076 // Fix up custom header name/value pairs...
1077 $ops = array_map( [ $this, 'sanitizeOpHeaders' ], $ops );
1079 // Build up a list of FileOps...
1080 $performOps = $this->getOperationsInternal( $ops );
1082 // Acquire any locks as needed...
1083 if ( empty( $opts['nonLocking'] ) ) {
1084 // Build up a list of files to lock...
1085 $paths = $this->getPathsToLockForOpsInternal( $performOps );
1086 // Try to lock those files for the scope of this function...
1088 $scopeLock = $this->getScopedFileLocks( $paths, 'mixed', $status );
1089 if ( !$status->isOK() ) {
1090 return $status; // abort
1094 // Clear any file cache entries (after locks acquired)
1095 if ( empty( $opts['preserveCache'] ) ) {
1096 $this->clearCache();
1099 // Build the list of paths involved
1100 $paths = [];
1101 foreach ( $performOps as $performOp ) {
1102 $paths = array_merge( $paths, $performOp->storagePathsRead() );
1103 $paths = array_merge( $paths, $performOp->storagePathsChanged() );
1106 // Enlarge the cache to fit the stat entries of these files
1107 $this->cheapCache->resize( max( 2 * count( $paths ), self::CACHE_CHEAP_SIZE ) );
1109 // Load from the persistent container caches
1110 $this->primeContainerCache( $paths );
1111 // Get the latest stat info for all the files (having locked them)
1112 $ok = $this->preloadFileStat( [ 'srcs' => $paths, 'latest' => true ] );
1114 if ( $ok ) {
1115 // Actually attempt the operation batch...
1116 $opts = $this->setConcurrencyFlags( $opts );
1117 $subStatus = FileOpBatch::attempt( $performOps, $opts, $this->fileJournal );
1118 } else {
1119 // If we could not even stat some files, then bail out...
1120 $subStatus = $this->newStatus( 'backend-fail-internal', $this->name );
1121 foreach ( $ops as $i => $op ) { // mark each op as failed
1122 $subStatus->success[$i] = false;
1123 ++$subStatus->failCount;
1125 $this->logger->error( get_class( $this ) . "-{$this->name} " .
1126 " stat failure; aborted operations: " . FormatJson::encode( $ops ) );
1129 // Merge errors into StatusValue fields
1130 $status->merge( $subStatus );
1131 $status->success = $subStatus->success; // not done in merge()
1133 // Shrink the stat cache back to normal size
1134 $this->cheapCache->resize( self::CACHE_CHEAP_SIZE );
1136 return $status;
1139 final protected function doQuickOperationsInternal( array $ops ) {
1140 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1141 $status = $this->newStatus();
1143 // Fix up custom header name/value pairs...
1144 $ops = array_map( [ $this, 'sanitizeOpHeaders' ], $ops );
1146 // Clear any file cache entries
1147 $this->clearCache();
1149 $supportedOps = [ 'create', 'store', 'copy', 'move', 'delete', 'describe', 'null' ];
1150 // Parallel ops may be disabled in config due to dependencies (e.g. needing popen())
1151 $async = ( $this->parallelize === 'implicit' && count( $ops ) > 1 );
1152 $maxConcurrency = $this->concurrency; // throttle
1153 /** @var StatusValue[] $statuses */
1154 $statuses = []; // array of (index => StatusValue)
1155 $fileOpHandles = []; // list of (index => handle) arrays
1156 $curFileOpHandles = []; // current handle batch
1157 // Perform the sync-only ops and build up op handles for the async ops...
1158 foreach ( $ops as $index => $params ) {
1159 if ( !in_array( $params['op'], $supportedOps ) ) {
1160 throw new FileBackendError( "Operation '{$params['op']}' is not supported." );
1162 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1163 $subStatus = $this->$method( [ 'async' => $async ] + $params );
1164 if ( $subStatus->value instanceof FileBackendStoreOpHandle ) { // async
1165 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1166 $fileOpHandles[] = $curFileOpHandles; // push this batch
1167 $curFileOpHandles = [];
1169 $curFileOpHandles[$index] = $subStatus->value; // keep index
1170 } else { // error or completed
1171 $statuses[$index] = $subStatus; // keep index
1174 if ( count( $curFileOpHandles ) ) {
1175 $fileOpHandles[] = $curFileOpHandles; // last batch
1177 // Do all the async ops that can be done concurrently...
1178 foreach ( $fileOpHandles as $fileHandleBatch ) {
1179 $statuses = $statuses + $this->executeOpHandlesInternal( $fileHandleBatch );
1181 // Marshall and merge all the responses...
1182 foreach ( $statuses as $index => $subStatus ) {
1183 $status->merge( $subStatus );
1184 if ( $subStatus->isOK() ) {
1185 $status->success[$index] = true;
1186 ++$status->successCount;
1187 } else {
1188 $status->success[$index] = false;
1189 ++$status->failCount;
1193 return $status;
1197 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1198 * The resulting StatusValue object fields will correspond
1199 * to the order in which the handles where given.
1201 * @param FileBackendStoreOpHandle[] $fileOpHandles
1203 * @throws FileBackendError
1204 * @return StatusValue[] Map of StatusValue objects
1206 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1207 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1209 foreach ( $fileOpHandles as $fileOpHandle ) {
1210 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle ) ) {
1211 throw new InvalidArgumentException( "Got a non-FileBackendStoreOpHandle object." );
1212 } elseif ( $fileOpHandle->backend->getName() !== $this->getName() ) {
1213 throw new InvalidArgumentException(
1214 "Got a FileBackendStoreOpHandle for the wrong backend." );
1217 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1218 foreach ( $fileOpHandles as $fileOpHandle ) {
1219 $fileOpHandle->closeResources();
1222 return $res;
1226 * @see FileBackendStore::executeOpHandlesInternal()
1228 * @param FileBackendStoreOpHandle[] $fileOpHandles
1230 * @throws FileBackendError
1231 * @return StatusValue[] List of corresponding StatusValue objects
1233 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1234 if ( count( $fileOpHandles ) ) {
1235 throw new LogicException( "Backend does not support asynchronous operations." );
1238 return [];
1242 * Normalize and filter HTTP headers from a file operation
1244 * This normalizes and strips long HTTP headers from a file operation.
1245 * Most headers are just numbers, but some are allowed to be long.
1246 * This function is useful for cleaning up headers and avoiding backend
1247 * specific errors, especially in the middle of batch file operations.
1249 * @param array $op Same format as doOperation()
1250 * @return array
1252 protected function sanitizeOpHeaders( array $op ) {
1253 static $longs = [ 'content-disposition' ];
1255 if ( isset( $op['headers'] ) ) { // op sets HTTP headers
1256 $newHeaders = [];
1257 foreach ( $op['headers'] as $name => $value ) {
1258 $name = strtolower( $name );
1259 $maxHVLen = in_array( $name, $longs ) ? INF : 255;
1260 if ( strlen( $name ) > 255 || strlen( $value ) > $maxHVLen ) {
1261 trigger_error( "Header '$name: $value' is too long." );
1262 } else {
1263 $newHeaders[$name] = strlen( $value ) ? $value : ''; // null/false => ""
1266 $op['headers'] = $newHeaders;
1269 return $op;
1272 final public function preloadCache( array $paths ) {
1273 $fullConts = []; // full container names
1274 foreach ( $paths as $path ) {
1275 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1276 $fullConts[] = $fullCont;
1278 // Load from the persistent file and container caches
1279 $this->primeContainerCache( $fullConts );
1280 $this->primeFileCache( $paths );
1283 final public function clearCache( array $paths = null ) {
1284 if ( is_array( $paths ) ) {
1285 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1286 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1288 if ( $paths === null ) {
1289 $this->cheapCache->clear();
1290 $this->expensiveCache->clear();
1291 } else {
1292 foreach ( $paths as $path ) {
1293 $this->cheapCache->clear( $path );
1294 $this->expensiveCache->clear( $path );
1297 $this->doClearCache( $paths );
1301 * Clears any additional stat caches for storage paths
1303 * @see FileBackend::clearCache()
1305 * @param array $paths Storage paths (optional)
1307 protected function doClearCache( array $paths = null ) {
1310 final public function preloadFileStat( array $params ) {
1311 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1312 $success = true; // no network errors
1314 $params['concurrency'] = ( $this->parallelize !== 'off' ) ? $this->concurrency : 1;
1315 $stats = $this->doGetFileStatMulti( $params );
1316 if ( $stats === null ) {
1317 return true; // not supported
1320 $latest = !empty( $params['latest'] ); // use latest data?
1321 foreach ( $stats as $path => $stat ) {
1322 $path = FileBackend::normalizeStoragePath( $path );
1323 if ( $path === null ) {
1324 continue; // this shouldn't happen
1326 if ( is_array( $stat ) ) { // file exists
1327 // Strongly consistent backends can automatically set "latest"
1328 $stat['latest'] = isset( $stat['latest'] ) ? $stat['latest'] : $latest;
1329 $this->cheapCache->set( $path, 'stat', $stat );
1330 $this->setFileCache( $path, $stat ); // update persistent cache
1331 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
1332 $this->cheapCache->set( $path, 'sha1',
1333 [ 'hash' => $stat['sha1'], 'latest' => $latest ] );
1335 if ( isset( $stat['xattr'] ) ) { // some backends store headers/metadata
1336 $stat['xattr'] = self::normalizeXAttributes( $stat['xattr'] );
1337 $this->cheapCache->set( $path, 'xattr',
1338 [ 'map' => $stat['xattr'], 'latest' => $latest ] );
1340 } elseif ( $stat === false ) { // file does not exist
1341 $this->cheapCache->set( $path, 'stat',
1342 $latest ? 'NOT_EXIST_LATEST' : 'NOT_EXIST' );
1343 $this->cheapCache->set( $path, 'xattr',
1344 [ 'map' => false, 'latest' => $latest ] );
1345 $this->cheapCache->set( $path, 'sha1',
1346 [ 'hash' => false, 'latest' => $latest ] );
1347 $this->logger->debug( __METHOD__ . ": File $path does not exist.\n" );
1348 } else { // an error occurred
1349 $success = false;
1350 $this->logger->warning( __METHOD__ . ": Could not stat file $path.\n" );
1354 return $success;
1358 * Get file stat information (concurrently if possible) for several files
1360 * @see FileBackend::getFileStat()
1362 * @param array $params Parameters include:
1363 * - srcs : list of source storage paths
1364 * - latest : use the latest available data
1365 * @return array|null Map of storage paths to array|bool|null (returns null if not supported)
1366 * @since 1.23
1368 protected function doGetFileStatMulti( array $params ) {
1369 return null; // not supported
1373 * Is this a key/value store where directories are just virtual?
1374 * Virtual directories exists in so much as files exists that are
1375 * prefixed with the directory path followed by a forward slash.
1377 * @return bool
1379 abstract protected function directoriesAreVirtual();
1382 * Check if a short container name is valid
1384 * This checks for length and illegal characters.
1385 * This may disallow certain characters that can appear
1386 * in the prefix used to make the full container name.
1388 * @param string $container
1389 * @return bool
1391 final protected static function isValidShortContainerName( $container ) {
1392 // Suffixes like '.xxx' (hex shard chars) or '.seg' (file segments)
1393 // might be used by subclasses. Reserve the dot character for sanity.
1394 // The only way dots end up in containers (e.g. resolveStoragePath)
1395 // is due to the wikiId container prefix or the above suffixes.
1396 return self::isValidContainerName( $container ) && !preg_match( '/[.]/', $container );
1400 * Check if a full container name is valid
1402 * This checks for length and illegal characters.
1403 * Limiting the characters makes migrations to other stores easier.
1405 * @param string $container
1406 * @return bool
1408 final protected static function isValidContainerName( $container ) {
1409 // This accounts for NTFS, Swift, and Ceph restrictions
1410 // and disallows directory separators or traversal characters.
1411 // Note that matching strings URL encode to the same string;
1412 // in Swift/Ceph, the length restriction is *after* URL encoding.
1413 return (bool)preg_match( '/^[a-z0-9][a-z0-9-_.]{0,199}$/i', $container );
1417 * Splits a storage path into an internal container name,
1418 * an internal relative file name, and a container shard suffix.
1419 * Any shard suffix is already appended to the internal container name.
1420 * This also checks that the storage path is valid and within this backend.
1422 * If the container is sharded but a suffix could not be determined,
1423 * this means that the path can only refer to a directory and can only
1424 * be scanned by looking in all the container shards.
1426 * @param string $storagePath
1427 * @return array (container, path, container suffix) or (null, null, null) if invalid
1429 final protected function resolveStoragePath( $storagePath ) {
1430 list( $backend, $shortCont, $relPath ) = self::splitStoragePath( $storagePath );
1431 if ( $backend === $this->name ) { // must be for this backend
1432 $relPath = self::normalizeContainerPath( $relPath );
1433 if ( $relPath !== null && self::isValidShortContainerName( $shortCont ) ) {
1434 // Get shard for the normalized path if this container is sharded
1435 $cShard = $this->getContainerShard( $shortCont, $relPath );
1436 // Validate and sanitize the relative path (backend-specific)
1437 $relPath = $this->resolveContainerPath( $shortCont, $relPath );
1438 if ( $relPath !== null ) {
1439 // Prepend any wiki ID prefix to the container name
1440 $container = $this->fullContainerName( $shortCont );
1441 if ( self::isValidContainerName( $container ) ) {
1442 // Validate and sanitize the container name (backend-specific)
1443 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1444 if ( $container !== null ) {
1445 return [ $container, $relPath, $cShard ];
1452 return [ null, null, null ];
1456 * Like resolveStoragePath() except null values are returned if
1457 * the container is sharded and the shard could not be determined
1458 * or if the path ends with '/'. The latter case is illegal for FS
1459 * backends and can confuse listings for object store backends.
1461 * This function is used when resolving paths that must be valid
1462 * locations for files. Directory and listing functions should
1463 * generally just use resolveStoragePath() instead.
1465 * @see FileBackendStore::resolveStoragePath()
1467 * @param string $storagePath
1468 * @return array (container, path) or (null, null) if invalid
1470 final protected function resolveStoragePathReal( $storagePath ) {
1471 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1472 if ( $cShard !== null && substr( $relPath, -1 ) !== '/' ) {
1473 return [ $container, $relPath ];
1476 return [ null, null ];
1480 * Get the container name shard suffix for a given path.
1481 * Any empty suffix means the container is not sharded.
1483 * @param string $container Container name
1484 * @param string $relPath Storage path relative to the container
1485 * @return string|null Returns null if shard could not be determined
1487 final protected function getContainerShard( $container, $relPath ) {
1488 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1489 if ( $levels == 1 || $levels == 2 ) {
1490 // Hash characters are either base 16 or 36
1491 $char = ( $base == 36 ) ? '[0-9a-z]' : '[0-9a-f]';
1492 // Get a regex that represents the shard portion of paths.
1493 // The concatenation of the captures gives us the shard.
1494 if ( $levels === 1 ) { // 16 or 36 shards per container
1495 $hashDirRegex = '(' . $char . ')';
1496 } else { // 256 or 1296 shards per container
1497 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1498 $hashDirRegex = $char . '/(' . $char . '{2})';
1499 } else { // short hash dir format (e.g. "a/b/c")
1500 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1503 // Allow certain directories to be above the hash dirs so as
1504 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1505 // They must be 2+ chars to avoid any hash directory ambiguity.
1506 $m = [];
1507 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1508 return '.' . implode( '', array_slice( $m, 1 ) );
1511 return null; // failed to match
1514 return ''; // no sharding
1518 * Check if a storage path maps to a single shard.
1519 * Container dirs like "a", where the container shards on "x/xy",
1520 * can reside on several shards. Such paths are tricky to handle.
1522 * @param string $storagePath Storage path
1523 * @return bool
1525 final public function isSingleShardPathInternal( $storagePath ) {
1526 list( , , $shard ) = $this->resolveStoragePath( $storagePath );
1528 return ( $shard !== null );
1532 * Get the sharding config for a container.
1533 * If greater than 0, then all file storage paths within
1534 * the container are required to be hashed accordingly.
1536 * @param string $container
1537 * @return array (integer levels, integer base, repeat flag) or (0, 0, false)
1539 final protected function getContainerHashLevels( $container ) {
1540 if ( isset( $this->shardViaHashLevels[$container] ) ) {
1541 $config = $this->shardViaHashLevels[$container];
1542 $hashLevels = (int)$config['levels'];
1543 if ( $hashLevels == 1 || $hashLevels == 2 ) {
1544 $hashBase = (int)$config['base'];
1545 if ( $hashBase == 16 || $hashBase == 36 ) {
1546 return [ $hashLevels, $hashBase, $config['repeat'] ];
1551 return [ 0, 0, false ]; // no sharding
1555 * Get a list of full container shard suffixes for a container
1557 * @param string $container
1558 * @return array
1560 final protected function getContainerSuffixes( $container ) {
1561 $shards = [];
1562 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1563 if ( $digits > 0 ) {
1564 $numShards = pow( $base, $digits );
1565 for ( $index = 0; $index < $numShards; $index++ ) {
1566 $shards[] = '.' . Wikimedia\base_convert( $index, 10, $base, $digits );
1570 return $shards;
1574 * Get the full container name, including the wiki ID prefix
1576 * @param string $container
1577 * @return string
1579 final protected function fullContainerName( $container ) {
1580 if ( $this->domainId != '' ) {
1581 return "{$this->domainId}-$container";
1582 } else {
1583 return $container;
1588 * Resolve a container name, checking if it's allowed by the backend.
1589 * This is intended for internal use, such as encoding illegal chars.
1590 * Subclasses can override this to be more restrictive.
1592 * @param string $container
1593 * @return string|null
1595 protected function resolveContainerName( $container ) {
1596 return $container;
1600 * Resolve a relative storage path, checking if it's allowed by the backend.
1601 * This is intended for internal use, such as encoding illegal chars or perhaps
1602 * getting absolute paths (e.g. FS based backends). Note that the relative path
1603 * may be the empty string (e.g. the path is simply to the container).
1605 * @param string $container Container name
1606 * @param string $relStoragePath Storage path relative to the container
1607 * @return string|null Path or null if not valid
1609 protected function resolveContainerPath( $container, $relStoragePath ) {
1610 return $relStoragePath;
1614 * Get the cache key for a container
1616 * @param string $container Resolved container name
1617 * @return string
1619 private function containerCacheKey( $container ) {
1620 return "filebackend:{$this->name}:{$this->domainId}:container:{$container}";
1624 * Set the cached info for a container
1626 * @param string $container Resolved container name
1627 * @param array $val Information to cache
1629 final protected function setContainerCache( $container, array $val ) {
1630 $this->memCache->set( $this->containerCacheKey( $container ), $val, 14 * 86400 );
1634 * Delete the cached info for a container.
1635 * The cache key is salted for a while to prevent race conditions.
1637 * @param string $container Resolved container name
1639 final protected function deleteContainerCache( $container ) {
1640 if ( !$this->memCache->delete( $this->containerCacheKey( $container ), 300 ) ) {
1641 trigger_error( "Unable to delete stat cache for container $container." );
1646 * Do a batch lookup from cache for container stats for all containers
1647 * used in a list of container names or storage paths objects.
1648 * This loads the persistent cache values into the process cache.
1650 * @param array $items
1652 final protected function primeContainerCache( array $items ) {
1653 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1655 $paths = []; // list of storage paths
1656 $contNames = []; // (cache key => resolved container name)
1657 // Get all the paths/containers from the items...
1658 foreach ( $items as $item ) {
1659 if ( self::isStoragePath( $item ) ) {
1660 $paths[] = $item;
1661 } elseif ( is_string( $item ) ) { // full container name
1662 $contNames[$this->containerCacheKey( $item )] = $item;
1665 // Get all the corresponding cache keys for paths...
1666 foreach ( $paths as $path ) {
1667 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1668 if ( $fullCont !== null ) { // valid path for this backend
1669 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1673 $contInfo = []; // (resolved container name => cache value)
1674 // Get all cache entries for these container cache keys...
1675 $values = $this->memCache->getMulti( array_keys( $contNames ) );
1676 foreach ( $values as $cacheKey => $val ) {
1677 $contInfo[$contNames[$cacheKey]] = $val;
1680 // Populate the container process cache for the backend...
1681 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1685 * Fill the backend-specific process cache given an array of
1686 * resolved container names and their corresponding cached info.
1687 * Only containers that actually exist should appear in the map.
1689 * @param array $containerInfo Map of resolved container names to cached info
1691 protected function doPrimeContainerCache( array $containerInfo ) {
1695 * Get the cache key for a file path
1697 * @param string $path Normalized storage path
1698 * @return string
1700 private function fileCacheKey( $path ) {
1701 return "filebackend:{$this->name}:{$this->domainId}:file:" . sha1( $path );
1705 * Set the cached stat info for a file path.
1706 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1707 * salting for the case when a file is created at a path were there was none before.
1709 * @param string $path Storage path
1710 * @param array $val Stat information to cache
1712 final protected function setFileCache( $path, array $val ) {
1713 $path = FileBackend::normalizeStoragePath( $path );
1714 if ( $path === null ) {
1715 return; // invalid storage path
1717 $mtime = ConvertibleTimestamp::convert( TS_UNIX, $val['mtime'] );
1718 $ttl = $this->memCache->adaptiveTTL( $mtime, 7 * 86400, 300, .1 );
1719 $key = $this->fileCacheKey( $path );
1720 // Set the cache unless it is currently salted.
1721 $this->memCache->set( $key, $val, $ttl );
1725 * Delete the cached stat info for a file path.
1726 * The cache key is salted for a while to prevent race conditions.
1727 * Since negatives (404s) are not cached, this does not need to be called when
1728 * a file is created at a path were there was none before.
1730 * @param string $path Storage path
1732 final protected function deleteFileCache( $path ) {
1733 $path = FileBackend::normalizeStoragePath( $path );
1734 if ( $path === null ) {
1735 return; // invalid storage path
1737 if ( !$this->memCache->delete( $this->fileCacheKey( $path ), 300 ) ) {
1738 trigger_error( "Unable to delete stat cache for file $path." );
1743 * Do a batch lookup from cache for file stats for all paths
1744 * used in a list of storage paths or FileOp objects.
1745 * This loads the persistent cache values into the process cache.
1747 * @param array $items List of storage paths
1749 final protected function primeFileCache( array $items ) {
1750 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1752 $paths = []; // list of storage paths
1753 $pathNames = []; // (cache key => storage path)
1754 // Get all the paths/containers from the items...
1755 foreach ( $items as $item ) {
1756 if ( self::isStoragePath( $item ) ) {
1757 $paths[] = FileBackend::normalizeStoragePath( $item );
1760 // Get rid of any paths that failed normalization...
1761 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1762 // Get all the corresponding cache keys for paths...
1763 foreach ( $paths as $path ) {
1764 list( , $rel, ) = $this->resolveStoragePath( $path );
1765 if ( $rel !== null ) { // valid path for this backend
1766 $pathNames[$this->fileCacheKey( $path )] = $path;
1769 // Get all cache entries for these file cache keys...
1770 $values = $this->memCache->getMulti( array_keys( $pathNames ) );
1771 foreach ( $values as $cacheKey => $val ) {
1772 $path = $pathNames[$cacheKey];
1773 if ( is_array( $val ) ) {
1774 $val['latest'] = false; // never completely trust cache
1775 $this->cheapCache->set( $path, 'stat', $val );
1776 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1777 $this->cheapCache->set( $path, 'sha1',
1778 [ 'hash' => $val['sha1'], 'latest' => false ] );
1780 if ( isset( $val['xattr'] ) ) { // some backends store headers/metadata
1781 $val['xattr'] = self::normalizeXAttributes( $val['xattr'] );
1782 $this->cheapCache->set( $path, 'xattr',
1783 [ 'map' => $val['xattr'], 'latest' => false ] );
1790 * Normalize file headers/metadata to the FileBackend::getFileXAttributes() format
1792 * @param array $xattr
1793 * @return array
1794 * @since 1.22
1796 final protected static function normalizeXAttributes( array $xattr ) {
1797 $newXAttr = [ 'headers' => [], 'metadata' => [] ];
1799 foreach ( $xattr['headers'] as $name => $value ) {
1800 $newXAttr['headers'][strtolower( $name )] = $value;
1803 foreach ( $xattr['metadata'] as $name => $value ) {
1804 $newXAttr['metadata'][strtolower( $name )] = $value;
1807 return $newXAttr;
1811 * Set the 'concurrency' option from a list of operation options
1813 * @param array $opts Map of operation options
1814 * @return array
1816 final protected function setConcurrencyFlags( array $opts ) {
1817 $opts['concurrency'] = 1; // off
1818 if ( $this->parallelize === 'implicit' ) {
1819 if ( !isset( $opts['parallelize'] ) || $opts['parallelize'] ) {
1820 $opts['concurrency'] = $this->concurrency;
1822 } elseif ( $this->parallelize === 'explicit' ) {
1823 if ( !empty( $opts['parallelize'] ) ) {
1824 $opts['concurrency'] = $this->concurrency;
1828 return $opts;
1832 * Get the content type to use in HEAD/GET requests for a file
1834 * @param string $storagePath
1835 * @param string|null $content File data
1836 * @param string|null $fsPath File system path
1837 * @return string MIME type
1839 protected function getContentType( $storagePath, $content, $fsPath ) {
1840 if ( $this->mimeCallback ) {
1841 return call_user_func_array( $this->mimeCallback, func_get_args() );
1844 $mime = null;
1845 if ( $fsPath !== null && function_exists( 'finfo_file' ) ) {
1846 $finfo = finfo_open( FILEINFO_MIME_TYPE );
1847 $mime = finfo_file( $finfo, $fsPath );
1848 finfo_close( $finfo );
1851 return is_string( $mime ) ? $mime : 'unknown/unknown';
1856 * FileBackendStore helper class for performing asynchronous file operations.
1858 * For example, calling FileBackendStore::createInternal() with the "async"
1859 * param flag may result in a StatusValue that contains this object as a value.
1860 * This class is largely backend-specific and is mostly just "magic" to be
1861 * passed to FileBackendStore::executeOpHandlesInternal().
1863 abstract class FileBackendStoreOpHandle {
1864 /** @var array */
1865 public $params = []; // params to caller functions
1866 /** @var FileBackendStore */
1867 public $backend;
1868 /** @var array */
1869 public $resourcesToClose = [];
1871 public $call; // string; name that identifies the function called
1874 * Close all open file handles
1876 public function closeResources() {
1877 array_map( 'fclose', $this->resourcesToClose );
1882 * FileBackendStore helper function to handle listings that span container shards.
1883 * Do not use this class from places outside of FileBackendStore.
1885 * @ingroup FileBackend
1887 abstract class FileBackendStoreShardListIterator extends FilterIterator {
1888 /** @var FileBackendStore */
1889 protected $backend;
1891 /** @var array */
1892 protected $params;
1894 /** @var string Full container name */
1895 protected $container;
1897 /** @var string Resolved relative path */
1898 protected $directory;
1900 /** @var array */
1901 protected $multiShardPaths = []; // (rel path => 1)
1904 * @param FileBackendStore $backend
1905 * @param string $container Full storage container name
1906 * @param string $dir Storage directory relative to container
1907 * @param array $suffixes List of container shard suffixes
1908 * @param array $params
1910 public function __construct(
1911 FileBackendStore $backend, $container, $dir, array $suffixes, array $params
1913 $this->backend = $backend;
1914 $this->container = $container;
1915 $this->directory = $dir;
1916 $this->params = $params;
1918 $iter = new AppendIterator();
1919 foreach ( $suffixes as $suffix ) {
1920 $iter->append( $this->listFromShard( $this->container . $suffix ) );
1923 parent::__construct( $iter );
1926 public function accept() {
1927 $rel = $this->getInnerIterator()->current(); // path relative to given directory
1928 $path = $this->params['dir'] . "/{$rel}"; // full storage path
1929 if ( $this->backend->isSingleShardPathInternal( $path ) ) {
1930 return true; // path is only on one shard; no issue with duplicates
1931 } elseif ( isset( $this->multiShardPaths[$rel] ) ) {
1932 // Don't keep listing paths that are on multiple shards
1933 return false;
1934 } else {
1935 $this->multiShardPaths[$rel] = 1;
1937 return true;
1941 public function rewind() {
1942 parent::rewind();
1943 $this->multiShardPaths = [];
1947 * Get the list for a given container shard
1949 * @param string $container Resolved container name
1950 * @return Iterator
1952 abstract protected function listFromShard( $container );
1956 * Iterator for listing directories
1958 class FileBackendStoreShardDirIterator extends FileBackendStoreShardListIterator {
1959 protected function listFromShard( $container ) {
1960 $list = $this->backend->getDirectoryListInternal(
1961 $container, $this->directory, $this->params );
1962 if ( $list === null ) {
1963 return new ArrayIterator( [] );
1964 } else {
1965 return is_array( $list ) ? new ArrayIterator( $list ) : $list;
1971 * Iterator for listing regular files
1973 class FileBackendStoreShardFileIterator extends FileBackendStoreShardListIterator {
1974 protected function listFromShard( $container ) {
1975 $list = $this->backend->getFileListInternal(
1976 $container, $this->directory, $this->params );
1977 if ( $list === null ) {
1978 return new ArrayIterator( [] );
1979 } else {
1980 return is_array( $list ) ? new ArrayIterator( $list ) : $list;