26use InvalidArgumentException;
32use Wikimedia\AtEase\AtEase;
48use Wikimedia\Timestamp\ConvertibleTimestamp;
88 protected const RES_ABSENT =
false;
90 protected const RES_ERROR =
null;
93 protected const ABSENT_NORMAL =
'FNE-N';
95 protected const ABSENT_LATEST =
'FNE-L';
111 parent::__construct( $config );
112 $this->mimeCallback = $config[
'mimeCallback'] ??
null;
114 $this->memCache = WANObjectCache::newEmpty();
115 $this->cheapCache =
new MapCacheLRU( self::CACHE_CHEAP_SIZE );
116 $this->expensiveCache =
new MapCacheLRU( self::CACHE_EXPENSIVE_SIZE );
127 return min( $this->maxFileSize, PHP_INT_MAX );
165 $status = $this->
newStatus(
'backend-fail-maxsize',
170 if (
$params[
'dstExists'] ??
true ) {
208 $status = $this->
newStatus(
'backend-fail-maxsize',
213 if (
$params[
'dstExists'] ??
true ) {
253 if (
$params[
'dstExists'] ??
true ) {
324 if (
$params[
'dstExists'] ??
true ) {
356 if ( count(
$params[
'headers'] ) ) {
395 $scopeLockS = $this->
getScopedFileLocks( $params[
'srcs'], LockManager::LOCK_UW, $status );
396 if ( $status->isOK() ) {
398 $start_time = microtime(
true );
400 $sec = microtime(
true ) - $start_time;
401 if ( !$status->isOK() ) {
402 $this->logger->error( static::class .
"-{$this->name}" .
403 " failed to concatenate " . count(
$params[
'srcs'] ) .
" file(s) [$sec sec]" );
422 AtEase::suppressWarnings();
423 $ok = ( is_file( $tmpPath ) && filesize( $tmpPath ) == 0 );
424 AtEase::restoreWarnings();
426 $status->fatal(
'backend-fail-opentemp', $tmpPath );
433 foreach ( $fsFiles as
$path => &$fsFile ) {
438 $fsFile === self::RES_ERROR ?
'backend-fail-read' :
'backend-fail-notexists',
449 $tmpHandle = fopen( $tmpPath,
'ab' );
450 if ( $tmpHandle ===
false ) {
451 $status->fatal(
'backend-fail-opentemp', $tmpPath );
457 foreach ( $fsFiles as $virtualSource => $fsFile ) {
459 $sourceHandle = fopen( $fsFile->getPath(),
'rb' );
460 if ( $sourceHandle ===
false ) {
461 fclose( $tmpHandle );
462 $status->fatal(
'backend-fail-read', $virtualSource );
467 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
468 fclose( $sourceHandle );
469 fclose( $tmpHandle );
470 $status->fatal(
'backend-fail-writetemp', $tmpPath );
474 fclose( $sourceHandle );
476 if ( !fclose( $tmpHandle ) ) {
477 $status->fatal(
'backend-fail-closetemp', $tmpPath );
496 if ( $dir ===
null ) {
497 $status->fatal(
'backend-fail-invalidpath',
$params[
'dir'] );
502 if ( $shard !==
null ) {
505 $this->logger->debug( __METHOD__ .
": iterating over all container shards." );
533 if ( $dir ===
null ) {
534 $status->fatal(
'backend-fail-invalidpath',
$params[
'dir'] );
539 if ( $shard !==
null ) {
542 $this->logger->debug( __METHOD__ .
": iterating over all container shards." );
570 if ( $dir ===
null ) {
571 $status->fatal(
'backend-fail-invalidpath',
$params[
'dir'] );
576 if ( $shard !==
null ) {
579 $this->logger->debug( __METHOD__ .
": iterating over all container shards." );
609 if ( $subDirsRel !==
null ) {
610 foreach ( $subDirsRel as $subDirRel ) {
611 $subDir =
$params[
'dir'] .
"/{$subDirRel}";
612 $status->merge( $this->
doClean( [
'dir' => $subDir ] +
$params ) );
614 unset( $subDirsRel );
619 if ( $dir ===
null ) {
620 $status->fatal(
'backend-fail-invalidpath',
$params[
'dir'] );
626 $filesLockEx = [
$params[
'dir'] ];
628 $scopedLockE = $this->
getScopedFileLocks( $filesLockEx, LockManager::LOCK_EX, $status );
629 if ( !$status->isOK() ) {
633 if ( $shard !==
null ) {
637 $this->logger->debug( __METHOD__ .
": iterating over all container shards." );
665 if ( is_array( $stat ) ) {
669 return $stat === self::RES_ABSENT ? false : self::EXISTENCE_ERROR;
677 if ( is_array( $stat ) ) {
678 return $stat[
'mtime'];
681 return self::TIMESTAMP_FAIL;
689 if ( is_array( $stat ) ) {
690 return $stat[
'size'];
693 return self::SIZE_FAIL;
701 if (
$path ===
null ) {
702 return self::STAT_ERROR;
707 $latest = !empty(
$params[
'latest'] );
709 $requireSHA1 = !empty(
$params[
'requireSHA1'] );
711 $stat = $this->cheapCache->getField(
$path,
'stat', self::CACHE_TTL );
720 ( $requireSHA1 && is_array( $stat ) && !isset( $stat[
'sha1'] ) )
724 $stat = $this->cheapCache->getField(
$path,
'stat', self::CACHE_TTL );
728 if ( is_array( $stat ) ) {
730 ( !$latest || !empty( $stat[
'latest'] ) ) &&
731 ( !$requireSHA1 || isset( $stat[
'sha1'] ) )
735 } elseif ( $stat === self::ABSENT_LATEST ) {
736 return self::STAT_ABSENT;
737 } elseif ( $stat === self::ABSENT_NORMAL ) {
739 return self::STAT_ABSENT;
747 if ( is_array( $stat ) ) {
751 return $stat === self::RES_ERROR ? self::STAT_ERROR : self::STAT_ABSENT;
764 foreach ( $stats as
$path => $stat ) {
765 if ( is_array( $stat ) ) {
767 $stat[
'latest'] ??= $latest;
769 $this->cheapCache->setField(
$path,
'stat', $stat );
770 if ( isset( $stat[
'sha1'] ) ) {
772 $this->cheapCache->setField(
775 [
'hash' => $stat[
'sha1'],
'latest' => $latest ]
778 if ( isset( $stat[
'xattr'] ) ) {
781 $this->cheapCache->setField(
784 [
'map' => $stat[
'xattr'],
'latest' => $latest ]
789 } elseif ( $stat === self::RES_ABSENT ) {
790 $this->cheapCache->setField(
793 $latest ? self::ABSENT_LATEST : self::ABSENT_NORMAL
795 $this->cheapCache->setField(
798 [
'map' => self::XATTRS_FAIL,
'latest' => $latest ]
800 $this->cheapCache->setField(
803 [
'hash' => self::SHA1_FAIL,
'latest' => $latest ]
805 $this->logger->debug(
806 __METHOD__ .
': File {path} does not exist',
811 $this->logger->error(
812 __METHOD__ .
': Could not stat file {path}',
834 foreach ( $contents as
$path => $content ) {
835 if ( !is_string( $content ) ) {
836 $contents[
$path] = self::CONTENT_FAIL;
852 if ( $fsFile instanceof
FSFile ) {
853 AtEase::suppressWarnings();
854 $content = file_get_contents( $fsFile->getPath() );
855 AtEase::restoreWarnings();
856 $contents[
$path] = is_string( $content ) ? $content : self::RES_ERROR;
859 $contents[
$path] = $fsFile;
871 if (
$path ===
null ) {
872 return self::XATTRS_FAIL;
874 $latest = !empty(
$params[
'latest'] );
875 if ( $this->cheapCache->hasField(
$path,
'xattr', self::CACHE_TTL ) ) {
876 $stat = $this->cheapCache->getField(
$path,
'xattr' );
879 if ( !$latest || $stat[
'latest'] ) {
884 if ( is_array( $fields ) ) {
886 $this->cheapCache->setField(
889 [
'map' => $fields,
'latest' => $latest ]
891 } elseif ( $fields === self::RES_ABSENT ) {
892 $this->cheapCache->setField(
895 [
'map' => self::XATTRS_FAIL,
'latest' => $latest ]
898 $fields = self::XATTRS_FAIL;
911 return [
'headers' => [],
'metadata' => [] ];
919 if (
$path ===
null ) {
920 return self::SHA1_FAIL;
922 $latest = !empty(
$params[
'latest'] );
923 if ( $this->cheapCache->hasField(
$path,
'sha1', self::CACHE_TTL ) ) {
924 $stat = $this->cheapCache->getField(
$path,
'sha1' );
927 if ( !$latest || $stat[
'latest'] ) {
928 return $stat[
'hash'];
932 if ( is_string( $sha1 ) ) {
933 $this->cheapCache->setField(
936 [
'hash' => $sha1,
'latest' => $latest ]
938 } elseif ( $sha1 === self::RES_ABSENT ) {
939 $this->cheapCache->setField(
942 [
'hash' => self::SHA1_FAIL,
'latest' => $latest ]
945 $sha1 = self::SHA1_FAIL;
959 if ( $fsFile instanceof
FSFile ) {
960 $sha1 = $fsFile->getSha1Base36();
962 return is_string( $sha1 ) ? $sha1 : self::RES_ERROR;
965 return $fsFile === self::RES_ERROR ? self::RES_ERROR : self::RES_ABSENT;
974 return $fsFile ? $fsFile->getProps() : FSFile::placeholderProps();
984 $latest = !empty(
$params[
'latest'] );
986 foreach (
$params[
'srcs'] as $src ) {
988 if (
$path ===
null ) {
989 $fsFiles[$src] = self::RES_ERROR;
990 } elseif ( $this->expensiveCache->hasField(
$path,
'localRef' ) ) {
991 $val = $this->expensiveCache->getField(
$path,
'localRef' );
994 if ( !$latest || $val[
'latest'] ) {
995 $fsFiles[$src] = $val[
'object'];
1000 $params[
'srcs'] = array_diff(
$params[
'srcs'], array_keys( $fsFiles ) );
1002 if ( $fsFile instanceof
FSFile ) {
1003 $fsFiles[
$path] = $fsFile;
1004 $this->expensiveCache->setField(
1007 [
'object' => $fsFile,
'latest' => $latest ]
1011 $fsFiles[
$path] = $fsFile;
1051 return self::TEMPURL_ERROR;
1060 $params[
'options'] ??= [];
1064 if ( ( empty(
$params[
'headless'] ) ||
$params[
'headers'] ) && headers_sent() ) {
1065 print
"Headers already sent, terminating.\n";
1066 $status->fatal(
'backend-fail-stream',
$params[
'src'] );
1092 $this->getStreamerOptions()
1094 $res = $streamer->stream(
$params[
'headers'],
true,
$params[
'options'], $flags );
1101 $status->fatal(
'backend-fail-stream',
$params[
'src'] );
1109 if ( $dir ===
null ) {
1110 return self::EXISTENCE_ERROR;
1112 if ( $shard !==
null ) {
1115 $this->logger->debug( __METHOD__ .
": iterating over all container shards." );
1120 if ( $exists ===
true ) {
1123 } elseif ( $exists === self::RES_ERROR ) {
1124 $res = self::EXISTENCE_ERROR;
1144 if ( $dir ===
null ) {
1145 return self::EXISTENCE_ERROR;
1147 if ( $shard !==
null ) {
1151 $this->logger->debug( __METHOD__ .
": iterating over all container shards." );
1174 if ( $dir ===
null ) {
1175 return self::LIST_ERROR;
1177 if ( $shard !==
null ) {
1181 $this->logger->debug( __METHOD__ .
": iterating over all container shards." );
1215 'store' => StoreFileOp::class,
1216 'copy' => CopyFileOp::class,
1217 'move' => MoveFileOp::class,
1218 'delete' => DeleteFileOp::class,
1219 'create' => CreateFileOp::class,
1220 'describe' => DescribeFileOp::class,
1221 'null' => NullFileOp::class
1226 foreach ( $ops as $operation ) {
1227 $opName = $operation[
'op'];
1228 if ( isset( $supportedOps[$opName] ) ) {
1229 $class = $supportedOps[$opName];
1233 $performOps[] =
new $class( $this,
$params, $this->logger );
1254 $paths = [
'sh' => [],
'ex' => [] ];
1255 foreach ( $performOps as $fileOp ) {
1256 $paths[
'sh'] = array_merge( $paths[
'sh'], $fileOp->storagePathsRead() );
1257 $paths[
'ex'] = array_merge( $paths[
'ex'], $fileOp->storagePathsChanged() );
1260 $paths[
'sh'] = array_diff( $paths[
'sh'], $paths[
'ex'] );
1262 $paths[
'sh'] = array_merge( $paths[
'sh'], array_map(
'dirname', $paths[
'ex'] ) );
1265 LockManager::LOCK_UW => $paths[
'sh'],
1266 LockManager::LOCK_EX => $paths[
'ex']
1282 $ops = array_map( [ $this,
'sanitizeOpHeaders' ], $ops );
1286 foreach ( $fileOps as $fileOp ) {
1287 $pathsUsed = array_merge( $pathsUsed, $fileOp->storagePathsReadOrChanged() );
1291 if ( empty( $opts[
'nonLocking'] ) ) {
1295 if ( !$status->isOK() ) {
1301 if ( empty( $opts[
'preserveCache'] ) ) {
1306 $this->cheapCache->setMaxSize( max( 2 * count( $pathsUsed ), self::CACHE_CHEAP_SIZE ) );
1311 $ok = $this->
preloadFileStat( [
'srcs' => $pathsUsed,
'latest' =>
true ] );
1319 $subStatus = $this->
newStatus(
'backend-fail-internal', $this->name );
1320 foreach ( $ops as $i => $op ) {
1321 $subStatus->success[$i] =
false;
1322 ++$subStatus->failCount;
1324 $this->logger->error( static::class .
"-{$this->name} " .
1325 " stat failure; aborted operations: " . FormatJson::encode( $ops ) );
1329 $status->merge( $subStatus );
1330 $status->success = $subStatus->success;
1333 $this->cheapCache->setMaxSize( self::CACHE_CHEAP_SIZE );
1344 $ops = array_map( [ $this,
'sanitizeOpHeaders' ], $ops );
1348 foreach ( $fileOps as $fileOp ) {
1349 $pathsUsed = array_merge( $pathsUsed, $fileOp->storagePathsReadOrChanged() );
1356 $async = ( $this->parallelize ===
'implicit' && count( $ops ) > 1 );
1362 foreach ( $fileOps as $index => $fileOp ) {
1364 ? $fileOp->attemptAsyncQuick()
1365 : $fileOp->attemptQuick();
1367 if ( count( $batch ) >= $maxConcurrency ) {
1373 $batch[$index] = $subStatus->value;
1375 $statuses[$index] = $subStatus;
1378 if ( count( $batch ) ) {
1382 foreach ( $statuses as $index => $subStatus ) {
1383 $status->merge( $subStatus );
1384 if ( $subStatus->isOK() ) {
1385 $status->success[$index] =
true;
1386 ++$status->successCount;
1388 $status->success[$index] =
false;
1389 ++$status->failCount;
1411 foreach ( $fileOpHandles as $fileOpHandle ) {
1413 throw new InvalidArgumentException(
"Expected FileBackendStoreOpHandle object." );
1414 } elseif ( $fileOpHandle->backend->getName() !== $this->getName() ) {
1415 throw new InvalidArgumentException(
"Expected handle for this file backend." );
1420 foreach ( $fileOpHandles as $fileOpHandle ) {
1421 $fileOpHandle->closeResources();
1437 if ( count( $fileOpHandles ) ) {
1438 throw new FileBackendError(
"Backend does not support asynchronous operations." );
1456 static $longs = [
'content-disposition' ];
1458 if ( isset( $op[
'headers'] ) ) {
1460 foreach ( $op[
'headers'] as
$name => $value ) {
1462 $maxHVLen = in_array(
$name, $longs ) ? INF : 255;
1463 if ( strlen(
$name ) > 255 || strlen( $value ) > $maxHVLen ) {
1464 $this->logger->error(
"Header '{header}' is too long.", [
1465 'filebackend' => $this->name,
1466 'header' =>
"$name: $value",
1469 $newHeaders[
$name] = strlen( $value ) ? $value :
'';
1472 $op[
'headers'] = $newHeaders;
1480 foreach ( $paths as
$path ) {
1482 $fullConts[] = $fullCont;
1490 if ( is_array( $paths ) ) {
1491 $paths = array_map( [ FileBackend::class,
'normalizeStoragePath' ], $paths );
1492 $paths = array_filter( $paths,
'strlen' );
1494 if ( $paths ===
null ) {
1495 $this->cheapCache->clear();
1496 $this->expensiveCache->clear();
1498 foreach ( $paths as
$path ) {
1499 $this->cheapCache->clear(
$path );
1500 $this->expensiveCache->clear(
$path );
1521 $params[
'concurrency'] = ( $this->parallelize !==
'off' ) ? $this->concurrency : 1;
1523 if ( $stats ===
null ) {
1528 $latest = !empty(
$params[
'latest'] );
1591 return (
bool)preg_match(
'/^[a-z0-9][a-z0-9-_.]{0,199}$/i', $container );
1609 if ( $backend === $this->name ) {
1611 if ( $relPath !==
null && self::isValidShortContainerName( $shortCont ) ) {
1616 if ( $relPath !==
null ) {
1619 if ( self::isValidContainerName( $container ) ) {
1622 if ( $container !==
null ) {
1623 return [ $container, $relPath, $cShard ];
1630 return [
null,
null, null ];
1650 if ( $cShard !==
null && substr( $relPath, -1 ) !==
'/' ) {
1651 return [ $container, $relPath ];
1654 return [
null, null ];
1667 if ( $levels == 1 || $levels == 2 ) {
1669 $char = ( $base == 36 ) ?
'[0-9a-z]' :
'[0-9a-f]';
1672 if ( $levels === 1 ) {
1673 $hashDirRegex =
'(' . $char .
')';
1676 $hashDirRegex = $char .
'/(' . $char .
'{2})';
1678 $hashDirRegex =
'(' . $char .
')/(' . $char .
')';
1685 if ( preg_match(
"!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1686 return '.' . implode(
'', array_slice( $m, 1 ) );
1706 return ( $shard !==
null );
1718 if ( isset( $this->shardViaHashLevels[$container] ) ) {
1719 $config = $this->shardViaHashLevels[$container];
1720 $hashLevels = (int)$config[
'levels'];
1721 if ( $hashLevels == 1 || $hashLevels == 2 ) {
1722 $hashBase = (int)$config[
'base'];
1723 if ( $hashBase == 16 || $hashBase == 36 ) {
1724 return [ $hashLevels, $hashBase, $config[
'repeat'] ];
1729 return [ 0, 0, false ];
1741 if ( $digits > 0 ) {
1742 $numShards = $base ** $digits;
1743 for ( $index = 0; $index < $numShards; $index++ ) {
1744 $shards[] =
'.' . \Wikimedia\base_convert( (
string)$index, 10, $base, $digits );
1758 if ( $this->domainId !=
'' ) {
1759 return "{$this->domainId}-$container";
1790 return $relStoragePath;
1799 private function containerCacheKey( $container ) {
1800 return "filebackend:{$this->name}:{$this->domainId}:container:{$container}";
1810 if ( !$this->memCache->set( $this->containerCacheKey( $container ), $val, 14 * 86400 ) ) {
1811 $this->logger->warning(
"Unable to set stat cache for container {container}.",
1812 [
'filebackend' => $this->name,
'container' => $container ]
1824 if ( !$this->memCache->delete( $this->containerCacheKey( $container ), 300 ) ) {
1825 $this->logger->warning(
"Unable to delete stat cache for container {container}.",
1826 [
'filebackend' => $this->name,
'container' => $container ]
1845 foreach ( $items as $item ) {
1846 if ( self::isStoragePath( $item ) ) {
1848 } elseif ( is_string( $item ) ) {
1849 $contNames[$this->containerCacheKey( $item )] = $item;
1853 foreach ( $paths as
$path ) {
1855 if ( $fullCont !==
null ) {
1856 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1862 $values = $this->memCache->getMulti( array_keys( $contNames ) );
1863 foreach ( $values as $cacheKey => $val ) {
1864 $contInfo[$contNames[$cacheKey]] = $val;
1888 private function fileCacheKey(
$path ) {
1889 return "filebackend:{$this->name}:{$this->domainId}:file:" . sha1(
$path );
1902 if (
$path ===
null ) {
1905 $mtime = (int)ConvertibleTimestamp::convert( TS_UNIX, $val[
'mtime'] );
1906 $ttl = $this->memCache->adaptiveTTL( $mtime, 7 * 86400, 300, 0.1 );
1907 $key = $this->fileCacheKey(
$path );
1909 if ( !$this->memCache->set( $key, $val, $ttl ) ) {
1910 $this->logger->warning(
"Unable to set stat cache for file {path}.",
1911 [
'filebackend' => $this->name,
'path' =>
$path ]
1926 if (
$path ===
null ) {
1929 if ( !$this->memCache->delete( $this->fileCacheKey(
$path ), 300 ) ) {
1930 $this->logger->warning(
"Unable to delete stat cache for file {path}.",
1931 [
'filebackend' => $this->name,
'path' =>
$path ]
1950 foreach ( $items as $item ) {
1951 if ( self::isStoragePath( $item ) ) {
1953 if (
$path !==
null ) {
1959 foreach ( $paths as
$path ) {
1961 if ( $rel !==
null ) {
1962 $pathNames[$this->fileCacheKey(
$path )] =
$path;
1967 $values = $this->memCache->getMulti( array_keys( $pathNames ) );
1969 foreach ( array_filter( $values,
'is_array' ) as $cacheKey => $stat ) {
1970 $path = $pathNames[$cacheKey];
1973 unset( $stat[
'latest'] );
1975 $this->cheapCache->setField(
$path,
'stat', $stat );
1976 if ( isset( $stat[
'sha1'] ) && strlen( $stat[
'sha1'] ) == 31 ) {
1978 $this->cheapCache->setField(
1981 [
'hash' => $stat[
'sha1'],
'latest' =>
false ]
1984 if ( isset( $stat[
'xattr'] ) && is_array( $stat[
'xattr'] ) ) {
1987 $this->cheapCache->setField(
1990 [
'map' => $stat[
'xattr'],
'latest' =>
false ]
2004 $newXAttr = [
'headers' => [],
'metadata' => [] ];
2006 foreach ( $xattr[
'headers'] as
$name => $value ) {
2007 $newXAttr[
'headers'][strtolower(
$name )] = $value;
2010 foreach ( $xattr[
'metadata'] as
$name => $value ) {
2011 $newXAttr[
'metadata'][strtolower(
$name )] = $value;
2024 $opts[
'concurrency'] = 1;
2025 if ( $this->parallelize ===
'implicit' ) {
2026 if ( $opts[
'parallelize'] ??
true ) {
2029 } elseif ( $this->parallelize ===
'explicit' ) {
2030 if ( !empty( $opts[
'parallelize'] ) ) {
2048 if ( $this->mimeCallback ) {
2049 return call_user_func_array( $this->mimeCallback, func_get_args() );
2052 $mime = ( $fsPath !== null ) ? mime_content_type( $fsPath ) :
false;
2053 return $mime ?:
'unknown/unknown';
2058class_alias( FileBackendStore::class,
'FileBackendStore' );
array $params
The job parameters.
Resource locking handling.
Store key-value entries in a size-limited in-memory LRU cache.
Generic operation result class Has warning/error list, boolean status and arbitrary value.