3 * Base class for all backends using particular storage medium.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup FileBackend
24 use Wikimedia\AtEase\AtEase
;
25 use Wikimedia\Timestamp\ConvertibleTimestamp
;
28 * @brief Base class for all backends using particular storage medium.
30 * This class defines the methods as abstract that subclasses must implement.
31 * Outside callers should *not* use functions with "Internal" in the name.
33 * The FileBackend operations are implemented using basic functions
34 * such as storeInternal(), copyInternal(), deleteInternal() and the like.
35 * This class is also responsible for path resolution and sanitization.
37 * @ingroup FileBackend
40 abstract class FileBackendStore
extends FileBackend
{
41 /** @var WANObjectCache */
45 /** @var MapCacheLRU Map of paths to small (RAM/disk) cache items */
46 protected $cheapCache;
47 /** @var MapCacheLRU Map of paths to large (RAM/disk) cache items */
48 protected $expensiveCache;
50 /** @var array Map of container names to sharding config */
51 protected $shardViaHashLevels = [];
53 /** @var callable Method to get the MIME type of files */
54 protected $mimeCallback;
56 protected $maxFileSize = 4294967296; // integer bytes (4GiB)
58 const CACHE_TTL
= 10; // integer; TTL in seconds for process cache entries
59 const CACHE_CHEAP_SIZE
= 500; // integer; max entries in "cheap cache"
60 const CACHE_EXPENSIVE_SIZE
= 5; // integer; max entries in "expensive cache"
63 * @see FileBackend::__construct()
64 * Additional $config params include:
65 * - srvCache : BagOStuff cache to APC or the like.
66 * - wanCache : WANObjectCache object to use for persistent caching.
67 * - mimeCallback : Callback that takes (storage path, content, file system path) and
68 * returns the MIME type of the file or 'unknown/unknown'. The file
69 * system path parameter should be used if the content one is null.
71 * @param array $config
73 public function __construct( array $config ) {
74 parent
::__construct( $config );
75 $this->mimeCallback
= $config['mimeCallback'] ??
null;
76 $this->srvCache
= new EmptyBagOStuff(); // disabled by default
77 $this->memCache
= WANObjectCache
::newEmpty(); // disabled by default
78 $this->cheapCache
= new MapCacheLRU( self
::CACHE_CHEAP_SIZE
);
79 $this->expensiveCache
= new MapCacheLRU( self
::CACHE_EXPENSIVE_SIZE
);
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.
89 final public function maxFileSizeInternal() {
90 return $this->maxFileSize
;
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
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.
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 /** @noinspection PhpUnusedLocalVariableInspection */
124 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
125 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
126 $status = $this->newStatus( 'backend-fail-maxsize',
127 $params['dst'], $this->maxFileSizeInternal() );
129 $status = $this->doCreateInternal( $params );
130 $this->clearCache( [ $params['dst'] ] );
131 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
132 $this->deleteFileCache( $params['dst'] ); // persistent cache
140 * @see FileBackendStore::createInternal()
141 * @param array $params
142 * @return StatusValue
144 abstract protected function doCreateInternal( array $params );
147 * Store a file into the backend from a file on disk.
148 * This will overwrite any file that exists at the destination.
149 * Do not call this function from places outside FileBackend and FileOp.
152 * - src : source path on disk
153 * - dst : destination storage path
154 * - headers : HTTP header name/value map
155 * - async : StatusValue will be returned immediately if supported.
156 * If the StatusValue is OK, then its value field will be
157 * set to a FileBackendStoreOpHandle object.
158 * - dstExists : Whether a file exists at the destination (optimization).
159 * Callers can use "false" if no existing file is being changed.
161 * @param array $params
162 * @return StatusValue
164 final public function storeInternal( array $params ) {
165 /** @noinspection PhpUnusedLocalVariableInspection */
166 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
167 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
168 $status = $this->newStatus( 'backend-fail-maxsize',
169 $params['dst'], $this->maxFileSizeInternal() );
171 $status = $this->doStoreInternal( $params );
172 $this->clearCache( [ $params['dst'] ] );
173 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
174 $this->deleteFileCache( $params['dst'] ); // persistent cache
182 * @see FileBackendStore::storeInternal()
183 * @param array $params
184 * @return StatusValue
186 abstract protected function doStoreInternal( array $params );
189 * Copy a file from one storage path to another in the backend.
190 * This will overwrite any file that exists at the destination.
191 * Do not call this function from places outside FileBackend and FileOp.
194 * - src : source storage path
195 * - dst : destination storage path
196 * - ignoreMissingSource : do nothing if the source file does not exist
197 * - headers : HTTP header name/value map
198 * - async : StatusValue will be returned immediately if supported.
199 * If the StatusValue is OK, then its value field will be
200 * set to a FileBackendStoreOpHandle object.
201 * - dstExists : Whether a file exists at the destination (optimization).
202 * Callers can use "false" if no existing file is being changed.
204 * @param array $params
205 * @return StatusValue
207 final public function copyInternal( array $params ) {
208 /** @noinspection PhpUnusedLocalVariableInspection */
209 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
210 $status = $this->doCopyInternal( $params );
211 $this->clearCache( [ $params['dst'] ] );
212 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
213 $this->deleteFileCache( $params['dst'] ); // persistent cache
220 * @see FileBackendStore::copyInternal()
221 * @param array $params
222 * @return StatusValue
224 abstract protected function doCopyInternal( array $params );
227 * Delete a file at the storage path.
228 * Do not call this function from places outside FileBackend and FileOp.
231 * - src : source storage path
232 * - ignoreMissingSource : do nothing if the source file does not exist
233 * - async : StatusValue will be returned immediately if supported.
234 * If the StatusValue is OK, then its value field will be
235 * set to a FileBackendStoreOpHandle object.
237 * @param array $params
238 * @return StatusValue
240 final public function deleteInternal( array $params ) {
241 /** @noinspection PhpUnusedLocalVariableInspection */
242 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
243 $status = $this->doDeleteInternal( $params );
244 $this->clearCache( [ $params['src'] ] );
245 $this->deleteFileCache( $params['src'] ); // persistent cache
250 * @see FileBackendStore::deleteInternal()
251 * @param array $params
252 * @return StatusValue
254 abstract protected function doDeleteInternal( array $params );
257 * Move a file from one storage path to another in the backend.
258 * This will overwrite any file that exists at the destination.
259 * Do not call this function from places outside FileBackend and FileOp.
262 * - src : source storage path
263 * - dst : destination storage path
264 * - ignoreMissingSource : do nothing if the source file does not exist
265 * - headers : HTTP header name/value map
266 * - async : StatusValue will be returned immediately if supported.
267 * If the StatusValue is OK, then its value field will be
268 * set to a FileBackendStoreOpHandle object.
269 * - dstExists : Whether a file exists at the destination (optimization).
270 * Callers can use "false" if no existing file is being changed.
272 * @param array $params
273 * @return StatusValue
275 final public function moveInternal( array $params ) {
276 /** @noinspection PhpUnusedLocalVariableInspection */
277 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
278 $status = $this->doMoveInternal( $params );
279 $this->clearCache( [ $params['src'], $params['dst'] ] );
280 $this->deleteFileCache( $params['src'] ); // persistent cache
281 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
282 $this->deleteFileCache( $params['dst'] ); // persistent cache
289 * @see FileBackendStore::moveInternal()
290 * @param array $params
291 * @return StatusValue
293 protected function doMoveInternal( array $params ) {
294 unset( $params['async'] ); // two steps, won't work here :)
295 $nsrc = FileBackend
::normalizeStoragePath( $params['src'] );
296 $ndst = FileBackend
::normalizeStoragePath( $params['dst'] );
297 // Copy source to dest
298 $status = $this->copyInternal( $params );
299 if ( $nsrc !== $ndst && $status->isOK() ) {
300 // Delete source (only fails due to races or network problems)
301 $status->merge( $this->deleteInternal( [ 'src' => $params['src'] ] ) );
302 $status->setResult( true, $status->value
); // ignore delete() errors
309 * Alter metadata for a file at the storage path.
310 * Do not call this function from places outside FileBackend and FileOp.
313 * - src : source storage path
314 * - headers : HTTP header name/value map
315 * - async : StatusValue will be returned immediately if supported.
316 * If the StatusValue is OK, then its value field will be
317 * set to a FileBackendStoreOpHandle object.
319 * @param array $params
320 * @return StatusValue
322 final public function describeInternal( array $params ) {
323 /** @noinspection PhpUnusedLocalVariableInspection */
324 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
325 if ( count( $params['headers'] ) ) {
326 $status = $this->doDescribeInternal( $params );
327 $this->clearCache( [ $params['src'] ] );
328 $this->deleteFileCache( $params['src'] ); // persistent cache
330 $status = $this->newStatus(); // nothing to do
337 * @see FileBackendStore::describeInternal()
338 * @param array $params
339 * @return StatusValue
341 protected function doDescribeInternal( array $params ) {
342 return $this->newStatus();
346 * No-op file operation that does nothing.
347 * Do not call this function from places outside FileBackend and FileOp.
349 * @param array $params
350 * @return StatusValue
352 final public function nullInternal( array $params ) {
353 return $this->newStatus();
356 final public function concatenate( array $params ) {
357 /** @noinspection PhpUnusedLocalVariableInspection */
358 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
359 $status = $this->newStatus();
361 // Try to lock the source files for the scope of this function
362 /** @noinspection PhpUnusedLocalVariableInspection */
363 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager
::LOCK_UW
, $status );
364 if ( $status->isOK() ) {
365 // Actually do the file concatenation...
366 $start_time = microtime( true );
367 $status->merge( $this->doConcatenate( $params ) );
368 $sec = microtime( true ) - $start_time;
369 if ( !$status->isOK() ) {
370 $this->logger
->error( static::class . "-{$this->name}" .
371 " failed to concatenate " . count( $params['srcs'] ) . " file(s) [$sec sec]" );
379 * @see FileBackendStore::concatenate()
380 * @param array $params
381 * @return StatusValue
383 protected function doConcatenate( array $params ) {
384 $status = $this->newStatus();
385 $tmpPath = $params['dst']; // convenience
386 unset( $params['latest'] ); // sanity
388 // Check that the specified temp file is valid...
389 AtEase
::suppressWarnings();
390 $ok = ( is_file( $tmpPath ) && filesize( $tmpPath ) == 0 );
391 AtEase
::restoreWarnings();
392 if ( !$ok ) { // not present or not empty
393 $status->fatal( 'backend-fail-opentemp', $tmpPath );
398 // Get local FS versions of the chunks needed for the concatenation...
399 $fsFiles = $this->getLocalReferenceMulti( $params );
400 foreach ( $fsFiles as $path => &$fsFile ) {
401 if ( !$fsFile ) { // chunk failed to download?
402 $fsFile = $this->getLocalReference( [ 'src' => $path ] );
403 if ( !$fsFile ) { // retry failed?
404 $status->fatal( 'backend-fail-read', $path );
410 unset( $fsFile ); // unset reference so we can reuse $fsFile
412 // Get a handle for the destination temp file
413 $tmpHandle = fopen( $tmpPath, 'ab' );
414 if ( $tmpHandle === false ) {
415 $status->fatal( 'backend-fail-opentemp', $tmpPath );
420 // Build up the temp file using the source chunks (in order)...
421 foreach ( $fsFiles as $virtualSource => $fsFile ) {
422 // Get a handle to the local FS version
423 $sourceHandle = fopen( $fsFile->getPath(), 'rb' );
424 if ( $sourceHandle === false ) {
425 fclose( $tmpHandle );
426 $status->fatal( 'backend-fail-read', $virtualSource );
430 // Append chunk to file (pass chunk size to avoid magic quotes)
431 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
432 fclose( $sourceHandle );
433 fclose( $tmpHandle );
434 $status->fatal( 'backend-fail-writetemp', $tmpPath );
438 fclose( $sourceHandle );
440 if ( !fclose( $tmpHandle ) ) {
441 $status->fatal( 'backend-fail-closetemp', $tmpPath );
446 clearstatcache(); // temp file changed
451 final protected function doPrepare( array $params ) {
452 /** @noinspection PhpUnusedLocalVariableInspection */
453 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
454 $status = $this->newStatus();
456 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
457 if ( $dir === null ) {
458 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
460 return $status; // invalid storage path
463 if ( $shard !== null ) { // confined to a single container/shard
464 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
465 } else { // directory is on several shards
466 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
467 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
468 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
469 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
477 * @see FileBackendStore::doPrepare()
478 * @param string $container
480 * @param array $params
481 * @return StatusValue
483 protected function doPrepareInternal( $container, $dir, array $params ) {
484 return $this->newStatus();
487 final protected function doSecure( array $params ) {
488 /** @noinspection PhpUnusedLocalVariableInspection */
489 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
490 $status = $this->newStatus();
492 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
493 if ( $dir === null ) {
494 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
496 return $status; // invalid storage path
499 if ( $shard !== null ) { // confined to a single container/shard
500 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
501 } else { // directory is on several shards
502 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
503 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
504 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
505 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
513 * @see FileBackendStore::doSecure()
514 * @param string $container
516 * @param array $params
517 * @return StatusValue
519 protected function doSecureInternal( $container, $dir, array $params ) {
520 return $this->newStatus();
523 final protected function doPublish( array $params ) {
524 /** @noinspection PhpUnusedLocalVariableInspection */
525 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
526 $status = $this->newStatus();
528 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
529 if ( $dir === null ) {
530 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
532 return $status; // invalid storage path
535 if ( $shard !== null ) { // confined to a single container/shard
536 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
537 } else { // directory is on several shards
538 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
539 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
540 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
541 $status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
549 * @see FileBackendStore::doPublish()
550 * @param string $container
552 * @param array $params
553 * @return StatusValue
555 protected function doPublishInternal( $container, $dir, array $params ) {
556 return $this->newStatus();
559 final protected function doClean( array $params ) {
560 /** @noinspection PhpUnusedLocalVariableInspection */
561 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
562 $status = $this->newStatus();
564 // Recursive: first delete all empty subdirs recursively
565 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
566 $subDirsRel = $this->getTopDirectoryList( [ 'dir' => $params['dir'] ] );
567 if ( $subDirsRel !== null ) { // no errors
568 foreach ( $subDirsRel as $subDirRel ) {
569 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
570 $status->merge( $this->doClean( [ 'dir' => $subDir ] +
$params ) );
572 unset( $subDirsRel ); // free directory for rmdir() on Windows (for FS backends)
576 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
577 if ( $dir === null ) {
578 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
580 return $status; // invalid storage path
583 // Attempt to lock this directory...
584 $filesLockEx = [ $params['dir'] ];
585 /** @noinspection PhpUnusedLocalVariableInspection */
586 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
587 if ( !$status->isOK() ) {
588 return $status; // abort
591 if ( $shard !== null ) { // confined to a single container/shard
592 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
593 $this->deleteContainerCache( $fullCont ); // purge cache
594 } else { // directory is on several shards
595 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
596 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
597 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
598 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
599 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
607 * @see FileBackendStore::doClean()
608 * @param string $container
610 * @param array $params
611 * @return StatusValue
613 protected function doCleanInternal( $container, $dir, array $params ) {
614 return $this->newStatus();
617 final public function fileExists( array $params ) {
618 /** @noinspection PhpUnusedLocalVariableInspection */
619 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
620 $stat = $this->getFileStat( $params );
622 return ( $stat === self
::UNKNOWN
) ? self
::UNKNOWN
: (bool)$stat;
625 final public function getFileTimestamp( array $params ) {
626 /** @noinspection PhpUnusedLocalVariableInspection */
627 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
628 $stat = $this->getFileStat( $params );
630 return $stat ?
$stat['mtime'] : false;
633 final public function getFileSize( array $params ) {
634 /** @noinspection PhpUnusedLocalVariableInspection */
635 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
636 $stat = $this->getFileStat( $params );
638 return $stat ?
$stat['size'] : false;
641 final public function getFileStat( array $params ) {
642 $path = self
::normalizeStoragePath( $params['src'] );
643 if ( $path === null ) {
644 return false; // invalid storage path
646 /** @noinspection PhpUnusedLocalVariableInspection */
647 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
649 $latest = !empty( $params['latest'] ); // use latest data?
650 $requireSHA1 = !empty( $params['requireSHA1'] ); // require SHA-1 if file exists?
653 $stat = $this->cheapCache
->getField( $path, 'stat', self
::CACHE_TTL
);
654 // Note that some backends, like SwiftFileBackend, sometimes set file stat process
655 // cache entries from mass object listings that do not include the SHA-1. In that
656 // case, loading the persistent stat cache will likely yield the SHA-1.
658 $stat === self
::UNKNOWN ||
659 ( $requireSHA1 && is_array( $stat ) && !isset( $stat['sha1'] ) )
661 $this->primeFileCache( [ $path ] ); // check persistent cache
665 $stat = $this->cheapCache
->getField( $path, 'stat', self
::CACHE_TTL
);
666 // If we want the latest data, check that this cached
667 // value was in fact fetched with the latest available data.
668 if ( is_array( $stat ) ) {
670 ( !$latest ||
$stat['latest'] ) &&
671 ( !$requireSHA1 ||
isset( $stat['sha1'] ) )
675 } elseif ( in_array( $stat, [ 'NOT_EXIST', 'NOT_EXIST_LATEST' ], true ) ) {
676 if ( !$latest ||
$stat === 'NOT_EXIST_LATEST' ) {
681 $stat = $this->doGetFileStat( $params );
683 if ( is_array( $stat ) ) { // file exists
684 // Strongly consistent backends can automatically set "latest"
685 $stat['latest'] = $stat['latest'] ??
$latest;
686 $this->cheapCache
->setField( $path, 'stat', $stat );
687 $this->setFileCache( $path, $stat ); // update persistent cache
688 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
689 $this->cheapCache
->setField( $path, 'sha1',
690 [ 'hash' => $stat['sha1'], 'latest' => $latest ] );
692 if ( isset( $stat['xattr'] ) ) { // some backends store headers/metadata
693 $stat['xattr'] = self
::normalizeXAttributes( $stat['xattr'] );
694 $this->cheapCache
->setField( $path, 'xattr',
695 [ 'map' => $stat['xattr'], 'latest' => $latest ] );
697 } elseif ( $stat === false ) { // file does not exist
698 $this->cheapCache
->setField( $path, 'stat', $latest ?
'NOT_EXIST_LATEST' : 'NOT_EXIST' );
699 $this->cheapCache
->setField( $path, 'xattr', [ 'map' => false, 'latest' => $latest ] );
700 $this->cheapCache
->setField( $path, 'sha1', [ 'hash' => false, 'latest' => $latest ] );
701 $this->logger
->debug( __METHOD__
. ': File {path} does not exist', [
704 } else { // an error occurred
705 $this->logger
->warning( __METHOD__
. ': Could not stat file {path}', [
714 * @see FileBackendStore::getFileStat()
715 * @param array $params
717 abstract protected function doGetFileStat( array $params );
719 public function getFileContentsMulti( array $params ) {
720 /** @noinspection PhpUnusedLocalVariableInspection */
721 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
723 $params = $this->setConcurrencyFlags( $params );
724 $contents = $this->doGetFileContentsMulti( $params );
730 * @see FileBackendStore::getFileContentsMulti()
731 * @param array $params
734 protected function doGetFileContentsMulti( array $params ) {
736 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
737 AtEase
::suppressWarnings();
738 $contents[$path] = $fsFile ?
file_get_contents( $fsFile->getPath() ) : false;
739 AtEase
::restoreWarnings();
745 final public function getFileXAttributes( array $params ) {
746 $path = self
::normalizeStoragePath( $params['src'] );
747 if ( $path === null ) {
748 return false; // invalid storage path
750 /** @noinspection PhpUnusedLocalVariableInspection */
751 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
752 $latest = !empty( $params['latest'] ); // use latest data?
753 if ( $this->cheapCache
->hasField( $path, 'xattr', self
::CACHE_TTL
) ) {
754 $stat = $this->cheapCache
->getField( $path, 'xattr' );
755 // If we want the latest data, check that this cached
756 // value was in fact fetched with the latest available data.
757 if ( !$latest ||
$stat['latest'] ) {
761 $fields = $this->doGetFileXAttributes( $params );
762 $fields = is_array( $fields ) ? self
::normalizeXAttributes( $fields ) : false;
763 $this->cheapCache
->setField( $path, 'xattr', [ 'map' => $fields, 'latest' => $latest ] );
769 * @see FileBackendStore::getFileXAttributes()
770 * @param array $params
771 * @return array[][]|false
773 protected function doGetFileXAttributes( array $params ) {
774 return [ 'headers' => [], 'metadata' => [] ]; // not supported
777 final public function getFileSha1Base36( array $params ) {
778 $path = self
::normalizeStoragePath( $params['src'] );
779 if ( $path === null ) {
780 return false; // invalid storage path
782 /** @noinspection PhpUnusedLocalVariableInspection */
783 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
784 $latest = !empty( $params['latest'] ); // use latest data?
785 if ( $this->cheapCache
->hasField( $path, 'sha1', self
::CACHE_TTL
) ) {
786 $stat = $this->cheapCache
->getField( $path, 'sha1' );
787 // If we want the latest data, check that this cached
788 // value was in fact fetched with the latest available data.
789 if ( !$latest ||
$stat['latest'] ) {
790 return $stat['hash'];
793 $hash = $this->doGetFileSha1Base36( $params );
794 $this->cheapCache
->setField( $path, 'sha1', [ 'hash' => $hash, 'latest' => $latest ] );
800 * @see FileBackendStore::getFileSha1Base36()
801 * @param array $params
802 * @return bool|string
804 protected function doGetFileSha1Base36( array $params ) {
805 $fsFile = $this->getLocalReference( $params );
809 return $fsFile->getSha1Base36();
813 final public function getFileProps( array $params ) {
814 /** @noinspection PhpUnusedLocalVariableInspection */
815 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
816 $fsFile = $this->getLocalReference( $params );
817 $props = $fsFile ?
$fsFile->getProps() : FSFile
::placeholderProps();
822 final public function getLocalReferenceMulti( array $params ) {
823 /** @noinspection PhpUnusedLocalVariableInspection */
824 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
826 $params = $this->setConcurrencyFlags( $params );
828 $fsFiles = []; // (path => FSFile)
829 $latest = !empty( $params['latest'] ); // use latest data?
830 // Reuse any files already in process cache...
831 foreach ( $params['srcs'] as $src ) {
832 $path = self
::normalizeStoragePath( $src );
833 if ( $path === null ) {
834 $fsFiles[$src] = null; // invalid storage path
835 } elseif ( $this->expensiveCache
->hasField( $path, 'localRef' ) ) {
836 $val = $this->expensiveCache
->getField( $path, 'localRef' );
837 // If we want the latest data, check that this cached
838 // value was in fact fetched with the latest available data.
839 if ( !$latest ||
$val['latest'] ) {
840 $fsFiles[$src] = $val['object'];
844 // Fetch local references of any remaning files...
845 $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
846 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
847 $fsFiles[$path] = $fsFile;
848 if ( $fsFile ) { // update the process cache...
849 $this->expensiveCache
->setField( $path, 'localRef',
850 [ 'object' => $fsFile, 'latest' => $latest ] );
858 * @see FileBackendStore::getLocalReferenceMulti()
859 * @param array $params
862 protected function doGetLocalReferenceMulti( array $params ) {
863 return $this->doGetLocalCopyMulti( $params );
866 final public function getLocalCopyMulti( array $params ) {
867 /** @noinspection PhpUnusedLocalVariableInspection */
868 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
870 $params = $this->setConcurrencyFlags( $params );
871 $tmpFiles = $this->doGetLocalCopyMulti( $params );
877 * @see FileBackendStore::getLocalCopyMulti()
878 * @param array $params
881 abstract protected function doGetLocalCopyMulti( array $params );
884 * @see FileBackend::getFileHttpUrl()
885 * @param array $params
886 * @return string|null
888 public function getFileHttpUrl( array $params ) {
889 return null; // not supported
892 final public function streamFile( array $params ) {
893 /** @noinspection PhpUnusedLocalVariableInspection */
894 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
895 $status = $this->newStatus();
897 // Always set some fields for subclass convenience
898 $params['options'] = $params['options'] ??
[];
899 $params['headers'] = $params['headers'] ??
[];
901 // Don't stream it out as text/html if there was a PHP error
902 if ( ( empty( $params['headless'] ) ||
$params['headers'] ) && headers_sent() ) {
903 print "Headers already sent, terminating.\n";
904 $status->fatal( 'backend-fail-stream', $params['src'] );
908 $status->merge( $this->doStreamFile( $params ) );
914 * @see FileBackendStore::streamFile()
915 * @param array $params
916 * @return StatusValue
918 protected function doStreamFile( array $params ) {
919 $status = $this->newStatus();
922 $flags |
= !empty( $params['headless'] ) ? HTTPFileStreamer
::STREAM_HEADLESS
: 0;
923 $flags |
= !empty( $params['allowOB'] ) ? HTTPFileStreamer
::STREAM_ALLOW_OB
: 0;
925 $fsFile = $this->getLocalReference( $params );
927 $streamer = new HTTPFileStreamer(
930 'obResetFunc' => $this->obResetFunc
,
931 'streamMimeFunc' => $this->streamMimeFunc
934 $res = $streamer->stream( $params['headers'], true, $params['options'], $flags );
937 HTTPFileStreamer
::send404Message( $params['src'], $flags );
941 $status->fatal( 'backend-fail-stream', $params['src'] );
947 final public function directoryExists( array $params ) {
948 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
949 if ( $dir === null ) {
950 return false; // invalid storage path
952 if ( $shard !== null ) { // confined to a single container/shard
953 return $this->doDirectoryExists( $fullCont, $dir, $params );
954 } else { // directory is on several shards
955 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
956 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
957 $res = false; // response
958 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
959 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
963 } elseif ( $exists === null ) { // error?
964 $res = self
::UNKNOWN
; // if we don't find anything, it is indeterminate
973 * @see FileBackendStore::directoryExists()
975 * @param string $container Resolved container name
976 * @param string $dir Resolved path relative to container
977 * @param array $params
980 abstract protected function doDirectoryExists( $container, $dir, array $params );
982 final public function getDirectoryList( array $params ) {
983 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
984 if ( $dir === null ) { // invalid storage path
985 return self
::UNKNOWN
;
987 if ( $shard !== null ) {
988 // File listing is confined to a single container/shard
989 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
991 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
992 // File listing spans multiple containers/shards
993 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
995 return new FileBackendStoreShardDirIterator( $this,
996 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
1001 * Do not call this function from places outside FileBackend
1003 * @see FileBackendStore::getDirectoryList()
1005 * @param string $container Resolved container name
1006 * @param string $dir Resolved path relative to container
1007 * @param array $params
1008 * @return Traversable|array|null Returns null on failure
1010 abstract public function getDirectoryListInternal( $container, $dir, array $params );
1012 final public function getFileList( array $params ) {
1013 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
1014 if ( $dir === null ) { // invalid storage path
1015 return self
::UNKNOWN
;
1017 if ( $shard !== null ) {
1018 // File listing is confined to a single container/shard
1019 return $this->getFileListInternal( $fullCont, $dir, $params );
1021 $this->logger
->debug( __METHOD__
. ": iterating over all container shards.\n" );
1022 // File listing spans multiple containers/shards
1023 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
1025 return new FileBackendStoreShardFileIterator( $this,
1026 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
1031 * Do not call this function from places outside FileBackend
1033 * @see FileBackendStore::getFileList()
1035 * @param string $container Resolved container name
1036 * @param string $dir Resolved path relative to container
1037 * @param array $params
1038 * @return Traversable|string[]|null Returns null on failure
1040 abstract public function getFileListInternal( $container, $dir, array $params );
1043 * Return a list of FileOp objects from a list of operations.
1044 * Do not call this function from places outside FileBackend.
1046 * The result must have the same number of items as the input.
1047 * An exception is thrown if an unsupported operation is requested.
1049 * @param array $ops Same format as doOperations()
1050 * @return FileOp[] List of FileOp objects
1051 * @throws FileBackendError
1053 final public function getOperationsInternal( array $ops ) {
1055 'store' => StoreFileOp
::class,
1056 'copy' => CopyFileOp
::class,
1057 'move' => MoveFileOp
::class,
1058 'delete' => DeleteFileOp
::class,
1059 'create' => CreateFileOp
::class,
1060 'describe' => DescribeFileOp
::class,
1061 'null' => NullFileOp
::class
1064 $performOps = []; // array of FileOp objects
1065 // Build up ordered array of FileOps...
1066 foreach ( $ops as $operation ) {
1067 $opName = $operation['op'];
1068 if ( isset( $supportedOps[$opName] ) ) {
1069 $class = $supportedOps[$opName];
1070 // Get params for this operation
1071 $params = $operation;
1072 // Append the FileOp class
1073 $performOps[] = new $class( $this, $params, $this->logger
);
1075 throw new FileBackendError( "Operation '$opName' is not supported." );
1083 * Get a list of storage paths to lock for a list of operations
1084 * Returns an array with LockManager::LOCK_UW (shared locks) and
1085 * LockManager::LOCK_EX (exclusive locks) keys, each corresponding
1086 * to a list of storage paths to be locked. All returned paths are
1089 * @param array $performOps List of FileOp objects
1090 * @return array (LockManager::LOCK_UW => path list, LockManager::LOCK_EX => path list)
1092 final public function getPathsToLockForOpsInternal( array $performOps ) {
1093 // Build up a list of files to lock...
1094 $paths = [ 'sh' => [], 'ex' => [] ];
1095 foreach ( $performOps as $fileOp ) {
1096 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1097 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1099 // Optimization: if doing an EX lock anyway, don't also set an SH one
1100 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1101 // Get a shared lock on the parent directory of each path changed
1102 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1105 LockManager
::LOCK_UW
=> $paths['sh'],
1106 LockManager
::LOCK_EX
=> $paths['ex']
1110 public function getScopedLocksForOps( array $ops, StatusValue
$status ) {
1111 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1113 return $this->getScopedFileLocks( $paths, 'mixed', $status );
1116 final protected function doOperationsInternal( array $ops, array $opts ) {
1117 /** @noinspection PhpUnusedLocalVariableInspection */
1118 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1119 $status = $this->newStatus();
1121 // Fix up custom header name/value pairs...
1122 $ops = array_map( [ $this, 'sanitizeOpHeaders' ], $ops );
1124 // Build up a list of FileOps...
1125 $performOps = $this->getOperationsInternal( $ops );
1127 // Acquire any locks as needed...
1128 if ( empty( $opts['nonLocking'] ) ) {
1129 // Build up a list of files to lock...
1130 $paths = $this->getPathsToLockForOpsInternal( $performOps );
1131 // Try to lock those files for the scope of this function...
1132 /** @noinspection PhpUnusedLocalVariableInspection */
1133 $scopeLock = $this->getScopedFileLocks( $paths, 'mixed', $status );
1134 if ( !$status->isOK() ) {
1135 return $status; // abort
1139 // Clear any file cache entries (after locks acquired)
1140 if ( empty( $opts['preserveCache'] ) ) {
1141 $this->clearCache();
1144 // Build the list of paths involved
1146 foreach ( $performOps as $performOp ) {
1147 $paths = array_merge( $paths, $performOp->storagePathsRead() );
1148 $paths = array_merge( $paths, $performOp->storagePathsChanged() );
1151 // Enlarge the cache to fit the stat entries of these files
1152 $this->cheapCache
->setMaxSize( max( 2 * count( $paths ), self
::CACHE_CHEAP_SIZE
) );
1154 // Load from the persistent container caches
1155 $this->primeContainerCache( $paths );
1156 // Get the latest stat info for all the files (having locked them)
1157 $ok = $this->preloadFileStat( [ 'srcs' => $paths, 'latest' => true ] );
1160 // Actually attempt the operation batch...
1161 $opts = $this->setConcurrencyFlags( $opts );
1162 $subStatus = FileOpBatch
::attempt( $performOps, $opts, $this->fileJournal
);
1164 // If we could not even stat some files, then bail out...
1165 $subStatus = $this->newStatus( 'backend-fail-internal', $this->name
);
1166 foreach ( $ops as $i => $op ) { // mark each op as failed
1167 $subStatus->success
[$i] = false;
1168 ++
$subStatus->failCount
;
1170 $this->logger
->error( static::class . "-{$this->name} " .
1171 " stat failure; aborted operations: " . FormatJson
::encode( $ops ) );
1174 // Merge errors into StatusValue fields
1175 $status->merge( $subStatus );
1176 $status->success
= $subStatus->success
; // not done in merge()
1178 // Shrink the stat cache back to normal size
1179 $this->cheapCache
->setMaxSize( self
::CACHE_CHEAP_SIZE
);
1184 final protected function doQuickOperationsInternal( array $ops ) {
1185 /** @noinspection PhpUnusedLocalVariableInspection */
1186 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1187 $status = $this->newStatus();
1189 // Fix up custom header name/value pairs...
1190 $ops = array_map( [ $this, 'sanitizeOpHeaders' ], $ops );
1192 // Clear any file cache entries
1193 $this->clearCache();
1195 $supportedOps = [ 'create', 'store', 'copy', 'move', 'delete', 'describe', 'null' ];
1196 // Parallel ops may be disabled in config due to dependencies (e.g. needing popen())
1197 $async = ( $this->parallelize
=== 'implicit' && count( $ops ) > 1 );
1198 $maxConcurrency = $this->concurrency
; // throttle
1199 /** @var StatusValue[] $statuses */
1200 $statuses = []; // array of (index => StatusValue)
1201 $fileOpHandles = []; // list of (index => handle) arrays
1202 $curFileOpHandles = []; // current handle batch
1203 // Perform the sync-only ops and build up op handles for the async ops...
1204 foreach ( $ops as $index => $params ) {
1205 if ( !in_array( $params['op'], $supportedOps ) ) {
1206 throw new FileBackendError( "Operation '{$params['op']}' is not supported." );
1208 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1209 $subStatus = $this->$method( [ 'async' => $async ] +
$params );
1210 if ( $subStatus->value
instanceof FileBackendStoreOpHandle
) { // async
1211 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1212 $fileOpHandles[] = $curFileOpHandles; // push this batch
1213 $curFileOpHandles = [];
1215 $curFileOpHandles[$index] = $subStatus->value
; // keep index
1216 } else { // error or completed
1217 $statuses[$index] = $subStatus; // keep index
1220 if ( count( $curFileOpHandles ) ) {
1221 $fileOpHandles[] = $curFileOpHandles; // last batch
1223 // Do all the async ops that can be done concurrently...
1224 foreach ( $fileOpHandles as $fileHandleBatch ) {
1225 $statuses = $statuses +
$this->executeOpHandlesInternal( $fileHandleBatch );
1227 // Marshall and merge all the responses...
1228 foreach ( $statuses as $index => $subStatus ) {
1229 $status->merge( $subStatus );
1230 if ( $subStatus->isOK() ) {
1231 $status->success
[$index] = true;
1232 ++
$status->successCount
;
1234 $status->success
[$index] = false;
1235 ++
$status->failCount
;
1243 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1244 * The resulting StatusValue object fields will correspond
1245 * to the order in which the handles where given.
1247 * @param FileBackendStoreOpHandle[] $fileOpHandles
1248 * @return StatusValue[] Map of StatusValue objects
1249 * @throws FileBackendError
1251 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1252 /** @noinspection PhpUnusedLocalVariableInspection */
1253 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1255 foreach ( $fileOpHandles as $fileOpHandle ) {
1256 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle
) ) {
1257 throw new InvalidArgumentException( "Expected FileBackendStoreOpHandle object." );
1258 } elseif ( $fileOpHandle->backend
->getName() !== $this->getName() ) {
1259 throw new InvalidArgumentException( "Expected handle for this file backend." );
1263 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1264 foreach ( $fileOpHandles as $fileOpHandle ) {
1265 $fileOpHandle->closeResources();
1272 * @see FileBackendStore::executeOpHandlesInternal()
1274 * @param FileBackendStoreOpHandle[] $fileOpHandles
1276 * @throws FileBackendError
1277 * @return StatusValue[] List of corresponding StatusValue objects
1279 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1280 if ( count( $fileOpHandles ) ) {
1281 throw new FileBackendError( "Backend does not support asynchronous operations." );
1288 * Normalize and filter HTTP headers from a file operation
1290 * This normalizes and strips long HTTP headers from a file operation.
1291 * Most headers are just numbers, but some are allowed to be long.
1292 * This function is useful for cleaning up headers and avoiding backend
1293 * specific errors, especially in the middle of batch file operations.
1295 * @param array $op Same format as doOperation()
1298 protected function sanitizeOpHeaders( array $op ) {
1299 static $longs = [ 'content-disposition' ];
1301 if ( isset( $op['headers'] ) ) { // op sets HTTP headers
1303 foreach ( $op['headers'] as $name => $value ) {
1304 $name = strtolower( $name );
1305 $maxHVLen = in_array( $name, $longs ) ? INF
: 255;
1306 if ( strlen( $name ) > 255 ||
strlen( $value ) > $maxHVLen ) {
1307 trigger_error( "Header '$name: $value' is too long." );
1309 $newHeaders[$name] = strlen( $value ) ?
$value : ''; // null/false => ""
1312 $op['headers'] = $newHeaders;
1318 final public function preloadCache( array $paths ) {
1319 $fullConts = []; // full container names
1320 foreach ( $paths as $path ) {
1321 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1322 $fullConts[] = $fullCont;
1324 // Load from the persistent file and container caches
1325 $this->primeContainerCache( $fullConts );
1326 $this->primeFileCache( $paths );
1329 final public function clearCache( array $paths = null ) {
1330 if ( is_array( $paths ) ) {
1331 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1332 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1334 if ( $paths === null ) {
1335 $this->cheapCache
->clear();
1336 $this->expensiveCache
->clear();
1338 foreach ( $paths as $path ) {
1339 $this->cheapCache
->clear( $path );
1340 $this->expensiveCache
->clear( $path );
1343 $this->doClearCache( $paths );
1347 * Clears any additional stat caches for storage paths
1349 * @see FileBackend::clearCache()
1351 * @param array|null $paths Storage paths (optional)
1353 protected function doClearCache( array $paths = null ) {
1356 final public function preloadFileStat( array $params ) {
1357 /** @noinspection PhpUnusedLocalVariableInspection */
1358 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1359 $success = true; // no network errors
1361 $params['concurrency'] = ( $this->parallelize
!== 'off' ) ?
$this->concurrency
: 1;
1362 $stats = $this->doGetFileStatMulti( $params );
1363 if ( $stats === null ) {
1364 return true; // not supported
1367 $latest = !empty( $params['latest'] ); // use latest data?
1368 foreach ( $stats as $path => $stat ) {
1369 $path = FileBackend
::normalizeStoragePath( $path );
1370 if ( $path === null ) {
1371 continue; // this shouldn't happen
1373 if ( is_array( $stat ) ) { // file exists
1374 // Strongly consistent backends can automatically set "latest"
1375 $stat['latest'] = $stat['latest'] ??
$latest;
1376 $this->cheapCache
->setField( $path, 'stat', $stat );
1377 $this->setFileCache( $path, $stat ); // update persistent cache
1378 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
1379 $this->cheapCache
->setField( $path, 'sha1',
1380 [ 'hash' => $stat['sha1'], 'latest' => $latest ] );
1382 if ( isset( $stat['xattr'] ) ) { // some backends store headers/metadata
1383 $stat['xattr'] = self
::normalizeXAttributes( $stat['xattr'] );
1384 $this->cheapCache
->setField( $path, 'xattr',
1385 [ 'map' => $stat['xattr'], 'latest' => $latest ] );
1387 } elseif ( $stat === false ) { // file does not exist
1388 $this->cheapCache
->setField( $path, 'stat',
1389 $latest ?
'NOT_EXIST_LATEST' : 'NOT_EXIST' );
1390 $this->cheapCache
->setField( $path, 'xattr',
1391 [ 'map' => false, 'latest' => $latest ] );
1392 $this->cheapCache
->setField( $path, 'sha1',
1393 [ 'hash' => false, 'latest' => $latest ] );
1394 $this->logger
->debug( __METHOD__
. ': File {path} does not exist', [
1397 } else { // an error occurred
1399 $this->logger
->warning( __METHOD__
. ': Could not stat file {path}', [
1409 * Get file stat information (concurrently if possible) for several files
1411 * @see FileBackend::getFileStat()
1413 * @param array $params Parameters include:
1414 * - srcs : list of source storage paths
1415 * - latest : use the latest available data
1416 * @return array|null Map of storage paths to array|bool|null (returns null if not supported)
1419 protected function doGetFileStatMulti( array $params ) {
1420 return null; // not supported
1424 * Is this a key/value store where directories are just virtual?
1425 * Virtual directories exists in so much as files exists that are
1426 * prefixed with the directory path followed by a forward slash.
1430 abstract protected function directoriesAreVirtual();
1433 * Check if a short container name is valid
1435 * This checks for length and illegal characters.
1436 * This may disallow certain characters that can appear
1437 * in the prefix used to make the full container name.
1439 * @param string $container
1442 final protected static function isValidShortContainerName( $container ) {
1443 // Suffixes like '.xxx' (hex shard chars) or '.seg' (file segments)
1444 // might be used by subclasses. Reserve the dot character for sanity.
1445 // The only way dots end up in containers (e.g. resolveStoragePath)
1446 // is due to the wikiId container prefix or the above suffixes.
1447 return self
::isValidContainerName( $container ) && !preg_match( '/[.]/', $container );
1451 * Check if a full container name is valid
1453 * This checks for length and illegal characters.
1454 * Limiting the characters makes migrations to other stores easier.
1456 * @param string $container
1459 final protected static function isValidContainerName( $container ) {
1460 // This accounts for NTFS, Swift, and Ceph restrictions
1461 // and disallows directory separators or traversal characters.
1462 // Note that matching strings URL encode to the same string;
1463 // in Swift/Ceph, the length restriction is *after* URL encoding.
1464 return (bool)preg_match( '/^[a-z0-9][a-z0-9-_.]{0,199}$/i', $container );
1468 * Splits a storage path into an internal container name,
1469 * an internal relative file name, and a container shard suffix.
1470 * Any shard suffix is already appended to the internal container name.
1471 * This also checks that the storage path is valid and within this backend.
1473 * If the container is sharded but a suffix could not be determined,
1474 * this means that the path can only refer to a directory and can only
1475 * be scanned by looking in all the container shards.
1477 * @param string $storagePath
1478 * @return array (container, path, container suffix) or (null, null, null) if invalid
1480 final protected function resolveStoragePath( $storagePath ) {
1481 list( $backend, $shortCont, $relPath ) = self
::splitStoragePath( $storagePath );
1482 if ( $backend === $this->name
) { // must be for this backend
1483 $relPath = self
::normalizeContainerPath( $relPath );
1484 if ( $relPath !== null && self
::isValidShortContainerName( $shortCont ) ) {
1485 // Get shard for the normalized path if this container is sharded
1486 $cShard = $this->getContainerShard( $shortCont, $relPath );
1487 // Validate and sanitize the relative path (backend-specific)
1488 $relPath = $this->resolveContainerPath( $shortCont, $relPath );
1489 if ( $relPath !== null ) {
1490 // Prepend any wiki ID prefix to the container name
1491 $container = $this->fullContainerName( $shortCont );
1492 if ( self
::isValidContainerName( $container ) ) {
1493 // Validate and sanitize the container name (backend-specific)
1494 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1495 if ( $container !== null ) {
1496 return [ $container, $relPath, $cShard ];
1503 return [ null, null, null ];
1507 * Like resolveStoragePath() except null values are returned if
1508 * the container is sharded and the shard could not be determined
1509 * or if the path ends with '/'. The latter case is illegal for FS
1510 * backends and can confuse listings for object store backends.
1512 * This function is used when resolving paths that must be valid
1513 * locations for files. Directory and listing functions should
1514 * generally just use resolveStoragePath() instead.
1516 * @see FileBackendStore::resolveStoragePath()
1518 * @param string $storagePath
1519 * @return array (container, path) or (null, null) if invalid
1521 final protected function resolveStoragePathReal( $storagePath ) {
1522 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1523 if ( $cShard !== null && substr( $relPath, -1 ) !== '/' ) {
1524 return [ $container, $relPath ];
1527 return [ null, null ];
1531 * Get the container name shard suffix for a given path.
1532 * Any empty suffix means the container is not sharded.
1534 * @param string $container Container name
1535 * @param string $relPath Storage path relative to the container
1536 * @return string|null Returns null if shard could not be determined
1538 final protected function getContainerShard( $container, $relPath ) {
1539 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1540 if ( $levels == 1 ||
$levels == 2 ) {
1541 // Hash characters are either base 16 or 36
1542 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1543 // Get a regex that represents the shard portion of paths.
1544 // The concatenation of the captures gives us the shard.
1545 if ( $levels === 1 ) { // 16 or 36 shards per container
1546 $hashDirRegex = '(' . $char . ')';
1547 } else { // 256 or 1296 shards per container
1548 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1549 $hashDirRegex = $char . '/(' . $char . '{2})';
1550 } else { // short hash dir format (e.g. "a/b/c")
1551 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1554 // Allow certain directories to be above the hash dirs so as
1555 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1556 // They must be 2+ chars to avoid any hash directory ambiguity.
1558 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1559 return '.' . implode( '', array_slice( $m, 1 ) );
1562 return null; // failed to match
1565 return ''; // no sharding
1569 * Check if a storage path maps to a single shard.
1570 * Container dirs like "a", where the container shards on "x/xy",
1571 * can reside on several shards. Such paths are tricky to handle.
1573 * @param string $storagePath Storage path
1576 final public function isSingleShardPathInternal( $storagePath ) {
1577 list( , , $shard ) = $this->resolveStoragePath( $storagePath );
1579 return ( $shard !== null );
1583 * Get the sharding config for a container.
1584 * If greater than 0, then all file storage paths within
1585 * the container are required to be hashed accordingly.
1587 * @param string $container
1588 * @return array (integer levels, integer base, repeat flag) or (0, 0, false)
1590 final protected function getContainerHashLevels( $container ) {
1591 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1592 $config = $this->shardViaHashLevels
[$container];
1593 $hashLevels = (int)$config['levels'];
1594 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1595 $hashBase = (int)$config['base'];
1596 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1597 return [ $hashLevels, $hashBase, $config['repeat'] ];
1602 return [ 0, 0, false ]; // no sharding
1606 * Get a list of full container shard suffixes for a container
1608 * @param string $container
1611 final protected function getContainerSuffixes( $container ) {
1613 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1614 if ( $digits > 0 ) {
1615 $numShards = $base ** $digits;
1616 for ( $index = 0; $index < $numShards; $index++
) {
1617 $shards[] = '.' . Wikimedia\base_convert
( $index, 10, $base, $digits );
1625 * Get the full container name, including the wiki ID prefix
1627 * @param string $container
1630 final protected function fullContainerName( $container ) {
1631 if ( $this->domainId
!= '' ) {
1632 return "{$this->domainId}-$container";
1639 * Resolve a container name, checking if it's allowed by the backend.
1640 * This is intended for internal use, such as encoding illegal chars.
1641 * Subclasses can override this to be more restrictive.
1643 * @param string $container
1644 * @return string|null
1646 protected function resolveContainerName( $container ) {
1651 * Resolve a relative storage path, checking if it's allowed by the backend.
1652 * This is intended for internal use, such as encoding illegal chars or perhaps
1653 * getting absolute paths (e.g. FS based backends). Note that the relative path
1654 * may be the empty string (e.g. the path is simply to the container).
1656 * @param string $container Container name
1657 * @param string $relStoragePath Storage path relative to the container
1658 * @return string|null Path or null if not valid
1660 protected function resolveContainerPath( $container, $relStoragePath ) {
1661 return $relStoragePath;
1665 * Get the cache key for a container
1667 * @param string $container Resolved container name
1670 private function containerCacheKey( $container ) {
1671 return "filebackend:{$this->name}:{$this->domainId}:container:{$container}";
1675 * Set the cached info for a container
1677 * @param string $container Resolved container name
1678 * @param array $val Information to cache
1680 final protected function setContainerCache( $container, array $val ) {
1681 $this->memCache
->set( $this->containerCacheKey( $container ), $val, 14 * 86400 );
1685 * Delete the cached info for a container.
1686 * The cache key is salted for a while to prevent race conditions.
1688 * @param string $container Resolved container name
1690 final protected function deleteContainerCache( $container ) {
1691 if ( !$this->memCache
->delete( $this->containerCacheKey( $container ), 300 ) ) {
1692 trigger_error( "Unable to delete stat cache for container $container." );
1697 * Do a batch lookup from cache for container stats for all containers
1698 * used in a list of container names or storage paths objects.
1699 * This loads the persistent cache values into the process cache.
1701 * @param array $items
1703 final protected function primeContainerCache( array $items ) {
1704 /** @noinspection PhpUnusedLocalVariableInspection */
1705 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1707 $paths = []; // list of storage paths
1708 $contNames = []; // (cache key => resolved container name)
1709 // Get all the paths/containers from the items...
1710 foreach ( $items as $item ) {
1711 if ( self
::isStoragePath( $item ) ) {
1713 } elseif ( is_string( $item ) ) { // full container name
1714 $contNames[$this->containerCacheKey( $item )] = $item;
1717 // Get all the corresponding cache keys for paths...
1718 foreach ( $paths as $path ) {
1719 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1720 if ( $fullCont !== null ) { // valid path for this backend
1721 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1725 $contInfo = []; // (resolved container name => cache value)
1726 // Get all cache entries for these container cache keys...
1727 $values = $this->memCache
->getMulti( array_keys( $contNames ) );
1728 foreach ( $values as $cacheKey => $val ) {
1729 $contInfo[$contNames[$cacheKey]] = $val;
1732 // Populate the container process cache for the backend...
1733 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1737 * Fill the backend-specific process cache given an array of
1738 * resolved container names and their corresponding cached info.
1739 * Only containers that actually exist should appear in the map.
1741 * @param array $containerInfo Map of resolved container names to cached info
1743 protected function doPrimeContainerCache( array $containerInfo ) {
1747 * Get the cache key for a file path
1749 * @param string $path Normalized storage path
1752 private function fileCacheKey( $path ) {
1753 return "filebackend:{$this->name}:{$this->domainId}:file:" . sha1( $path );
1757 * Set the cached stat info for a file path.
1758 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1759 * salting for the case when a file is created at a path were there was none before.
1761 * @param string $path Storage path
1762 * @param array $val Stat information to cache
1764 final protected function setFileCache( $path, array $val ) {
1765 $path = FileBackend
::normalizeStoragePath( $path );
1766 if ( $path === null ) {
1767 return; // invalid storage path
1769 $mtime = ConvertibleTimestamp
::convert( TS_UNIX
, $val['mtime'] );
1770 $ttl = $this->memCache
->adaptiveTTL( $mtime, 7 * 86400, 300, 0.1 );
1771 $key = $this->fileCacheKey( $path );
1772 // Set the cache unless it is currently salted.
1773 $this->memCache
->set( $key, $val, $ttl );
1777 * Delete the cached stat info for a file path.
1778 * The cache key is salted for a while to prevent race conditions.
1779 * Since negatives (404s) are not cached, this does not need to be called when
1780 * a file is created at a path were there was none before.
1782 * @param string $path Storage path
1784 final protected function deleteFileCache( $path ) {
1785 $path = FileBackend
::normalizeStoragePath( $path );
1786 if ( $path === null ) {
1787 return; // invalid storage path
1789 if ( !$this->memCache
->delete( $this->fileCacheKey( $path ), 300 ) ) {
1790 trigger_error( "Unable to delete stat cache for file $path." );
1795 * Do a batch lookup from cache for file stats for all paths
1796 * used in a list of storage paths or FileOp objects.
1797 * This loads the persistent cache values into the process cache.
1799 * @param array $items List of storage paths
1801 final protected function primeFileCache( array $items ) {
1802 /** @noinspection PhpUnusedLocalVariableInspection */
1803 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1805 $paths = []; // list of storage paths
1806 $pathNames = []; // (cache key => storage path)
1807 // Get all the paths/containers from the items...
1808 foreach ( $items as $item ) {
1809 if ( self
::isStoragePath( $item ) ) {
1810 $paths[] = FileBackend
::normalizeStoragePath( $item );
1813 // Get rid of any paths that failed normalization...
1814 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1815 // Get all the corresponding cache keys for paths...
1816 foreach ( $paths as $path ) {
1817 list( , $rel, ) = $this->resolveStoragePath( $path );
1818 if ( $rel !== null ) { // valid path for this backend
1819 $pathNames[$this->fileCacheKey( $path )] = $path;
1822 // Get all cache entries for these file cache keys...
1823 $values = $this->memCache
->getMulti( array_keys( $pathNames ) );
1824 foreach ( $values as $cacheKey => $val ) {
1825 $path = $pathNames[$cacheKey];
1826 if ( is_array( $val ) ) {
1827 $val['latest'] = false; // never completely trust cache
1828 $this->cheapCache
->setField( $path, 'stat', $val );
1829 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1830 $this->cheapCache
->setField( $path, 'sha1',
1831 [ 'hash' => $val['sha1'], 'latest' => false ] );
1833 if ( isset( $val['xattr'] ) ) { // some backends store headers/metadata
1834 $val['xattr'] = self
::normalizeXAttributes( $val['xattr'] );
1835 $this->cheapCache
->setField( $path, 'xattr',
1836 [ 'map' => $val['xattr'], 'latest' => false ] );
1843 * Normalize file headers/metadata to the FileBackend::getFileXAttributes() format
1845 * @param array $xattr
1849 final protected static function normalizeXAttributes( array $xattr ) {
1850 $newXAttr = [ 'headers' => [], 'metadata' => [] ];
1852 foreach ( $xattr['headers'] as $name => $value ) {
1853 $newXAttr['headers'][strtolower( $name )] = $value;
1856 foreach ( $xattr['metadata'] as $name => $value ) {
1857 $newXAttr['metadata'][strtolower( $name )] = $value;
1864 * Set the 'concurrency' option from a list of operation options
1866 * @param array $opts Map of operation options
1869 final protected function setConcurrencyFlags( array $opts ) {
1870 $opts['concurrency'] = 1; // off
1871 if ( $this->parallelize
=== 'implicit' ) {
1872 if ( !isset( $opts['parallelize'] ) ||
$opts['parallelize'] ) {
1873 $opts['concurrency'] = $this->concurrency
;
1875 } elseif ( $this->parallelize
=== 'explicit' ) {
1876 if ( !empty( $opts['parallelize'] ) ) {
1877 $opts['concurrency'] = $this->concurrency
;
1885 * Get the content type to use in HEAD/GET requests for a file
1887 * @param string $storagePath
1888 * @param string|null $content File data
1889 * @param string|null $fsPath File system path
1890 * @return string MIME type
1892 protected function getContentType( $storagePath, $content, $fsPath ) {
1893 if ( $this->mimeCallback
) {
1894 return call_user_func_array( $this->mimeCallback
, func_get_args() );
1897 $mime = ( $fsPath !== null ) ?
mime_content_type( $fsPath ) : false;
1898 return $mime ?
: 'unknown/unknown';