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
22 * @author Aaron Schulz
26 * @brief Base class for all backends using particular storage medium.
28 * This class defines the methods as abstract that subclasses must implement.
29 * Outside callers should *not* use functions with "Internal" in the name.
31 * The FileBackend operations are implemented using basic functions
32 * such as storeInternal(), copyInternal(), deleteInternal() and the like.
33 * This class is also responsible for path resolution and sanitization.
35 * @ingroup FileBackend
38 abstract class FileBackendStore
extends FileBackend
{
39 /** @var WANObjectCache */
41 /** @var ProcessCacheLRU Map of paths to small (RAM/disk) cache items */
42 protected $cheapCache;
43 /** @var ProcessCacheLRU Map of paths to large (RAM/disk) cache items */
44 protected $expensiveCache;
46 /** @var array Map of container names to sharding config */
47 protected $shardViaHashLevels = array();
49 /** @var callable Method to get the MIME type of files */
50 protected $mimeCallback;
52 protected $maxFileSize = 4294967296; // integer bytes (4GiB)
54 const CACHE_TTL
= 10; // integer; TTL in seconds for process cache entries
55 const CACHE_CHEAP_SIZE
= 500; // integer; max entries in "cheap cache"
56 const CACHE_EXPENSIVE_SIZE
= 5; // integer; max entries in "expensive cache"
59 * @see FileBackend::__construct()
60 * Additional $config params include:
61 * - wanCache : WANOBjectCache object to use for persistent caching.
62 * - mimeCallback : Callback that takes (storage path, content, file system path) and
63 * returns the MIME type of the file or 'unknown/unknown'. The file
64 * system path parameter should be used if the content one is null.
66 * @param array $config
68 public function __construct( array $config ) {
69 parent
::__construct( $config );
70 $this->mimeCallback
= isset( $config['mimeCallback'] )
71 ?
$config['mimeCallback']
72 : function ( $storagePath, $content, $fsPath ) {
73 // @todo handle the case of extension-less files using the contents
74 return StreamFile
::contentTypeFromPath( $storagePath ) ?
: 'unknown/unknown';
76 $this->memCache
= WANObjectCache
::newEmpty(); // disabled by default
77 $this->cheapCache
= new ProcessCacheLRU( self
::CACHE_CHEAP_SIZE
);
78 $this->expensiveCache
= new ProcessCacheLRU( self
::CACHE_EXPENSIVE_SIZE
);
82 * Get the maximum allowable file size given backend
83 * medium restrictions and basic performance constraints.
84 * Do not call this function from places outside FileBackend and FileOp.
88 final public function maxFileSizeInternal() {
89 return $this->maxFileSize
;
93 * Check if a file can be created or changed at a given storage path.
94 * FS backends should check if the parent directory exists, files can be
95 * written under it, and that any file already there is writable.
96 * Backends using key/value stores should check if the container exists.
98 * @param string $storagePath
101 abstract public function isPathUsableInternal( $storagePath );
104 * Create a file in the backend with the given contents.
105 * This will overwrite any file that exists at the destination.
106 * Do not call this function from places outside FileBackend and FileOp.
109 * - content : the raw file contents
110 * - dst : destination storage path
111 * - headers : HTTP header name/value map
112 * - async : Status will be returned immediately if supported.
113 * If the status is OK, then its value field will be
114 * set to a FileBackendStoreOpHandle object.
115 * - dstExists : Whether a file exists at the destination (optimization).
116 * Callers can use "false" if no existing file is being changed.
118 * @param array $params
121 final public function createInternal( array $params ) {
122 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
123 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
124 $status = Status
::newFatal( 'backend-fail-maxsize',
125 $params['dst'], $this->maxFileSizeInternal() );
127 $status = $this->doCreateInternal( $params );
128 $this->clearCache( array( $params['dst'] ) );
129 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
130 $this->deleteFileCache( $params['dst'] ); // persistent cache
138 * @see FileBackendStore::createInternal()
139 * @param array $params
142 abstract protected function doCreateInternal( array $params );
145 * Store a file into the backend from a file on disk.
146 * This will overwrite any file that exists at the destination.
147 * Do not call this function from places outside FileBackend and FileOp.
150 * - src : source path on disk
151 * - dst : destination storage path
152 * - headers : HTTP header name/value map
153 * - async : Status will be returned immediately if supported.
154 * If the status is OK, then its value field will be
155 * set to a FileBackendStoreOpHandle object.
156 * - dstExists : Whether a file exists at the destination (optimization).
157 * Callers can use "false" if no existing file is being changed.
159 * @param array $params
162 final public function storeInternal( array $params ) {
163 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
164 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
165 $status = Status
::newFatal( 'backend-fail-maxsize',
166 $params['dst'], $this->maxFileSizeInternal() );
168 $status = $this->doStoreInternal( $params );
169 $this->clearCache( array( $params['dst'] ) );
170 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
171 $this->deleteFileCache( $params['dst'] ); // persistent cache
179 * @see FileBackendStore::storeInternal()
180 * @param array $params
183 abstract protected function doStoreInternal( array $params );
186 * Copy a file from one storage path to another in the backend.
187 * This will overwrite any file that exists at the destination.
188 * Do not call this function from places outside FileBackend and FileOp.
191 * - src : source storage path
192 * - dst : destination storage path
193 * - ignoreMissingSource : do nothing if the source file does not exist
194 * - headers : HTTP header name/value map
195 * - async : Status will be returned immediately if supported.
196 * If the status is OK, then its value field will be
197 * set to a FileBackendStoreOpHandle object.
198 * - dstExists : Whether a file exists at the destination (optimization).
199 * Callers can use "false" if no existing file is being changed.
201 * @param array $params
204 final public function copyInternal( array $params ) {
205 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
206 $status = $this->doCopyInternal( $params );
207 $this->clearCache( array( $params['dst'] ) );
208 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
209 $this->deleteFileCache( $params['dst'] ); // persistent cache
216 * @see FileBackendStore::copyInternal()
217 * @param array $params
220 abstract protected function doCopyInternal( array $params );
223 * Delete a file at the storage path.
224 * Do not call this function from places outside FileBackend and FileOp.
227 * - src : source storage path
228 * - ignoreMissingSource : do nothing if the source file does not exist
229 * - async : Status will be returned immediately if supported.
230 * If the status is OK, then its value field will be
231 * set to a FileBackendStoreOpHandle object.
233 * @param array $params
236 final public function deleteInternal( array $params ) {
237 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
238 $status = $this->doDeleteInternal( $params );
239 $this->clearCache( array( $params['src'] ) );
240 $this->deleteFileCache( $params['src'] ); // persistent cache
245 * @see FileBackendStore::deleteInternal()
246 * @param array $params
249 abstract protected function doDeleteInternal( array $params );
252 * Move a file from one storage path to another in the backend.
253 * This will overwrite any file that exists at the destination.
254 * Do not call this function from places outside FileBackend and FileOp.
257 * - src : source storage path
258 * - dst : destination storage path
259 * - ignoreMissingSource : do nothing if the source file does not exist
260 * - headers : HTTP header name/value map
261 * - async : Status will be returned immediately if supported.
262 * If the status is OK, then its value field will be
263 * set to a FileBackendStoreOpHandle object.
264 * - dstExists : Whether a file exists at the destination (optimization).
265 * Callers can use "false" if no existing file is being changed.
267 * @param array $params
270 final public function moveInternal( array $params ) {
271 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
272 $status = $this->doMoveInternal( $params );
273 $this->clearCache( array( $params['src'], $params['dst'] ) );
274 $this->deleteFileCache( $params['src'] ); // persistent cache
275 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
276 $this->deleteFileCache( $params['dst'] ); // persistent cache
283 * @see FileBackendStore::moveInternal()
284 * @param array $params
287 protected function doMoveInternal( array $params ) {
288 unset( $params['async'] ); // two steps, won't work here :)
289 $nsrc = FileBackend
::normalizeStoragePath( $params['src'] );
290 $ndst = FileBackend
::normalizeStoragePath( $params['dst'] );
291 // Copy source to dest
292 $status = $this->copyInternal( $params );
293 if ( $nsrc !== $ndst && $status->isOK() ) {
294 // Delete source (only fails due to races or network problems)
295 $status->merge( $this->deleteInternal( array( 'src' => $params['src'] ) ) );
296 $status->setResult( true, $status->value
); // ignore delete() errors
303 * Alter metadata for a file at the storage path.
304 * Do not call this function from places outside FileBackend and FileOp.
307 * - src : source storage path
308 * - headers : HTTP header name/value map
309 * - async : Status will be returned immediately if supported.
310 * If the status is OK, then its value field will be
311 * set to a FileBackendStoreOpHandle object.
313 * @param array $params
316 final public function describeInternal( array $params ) {
317 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
318 if ( count( $params['headers'] ) ) {
319 $status = $this->doDescribeInternal( $params );
320 $this->clearCache( array( $params['src'] ) );
321 $this->deleteFileCache( $params['src'] ); // persistent cache
323 $status = Status
::newGood(); // nothing to do
330 * @see FileBackendStore::describeInternal()
331 * @param array $params
334 protected function doDescribeInternal( array $params ) {
335 return Status
::newGood();
339 * No-op file operation that does nothing.
340 * Do not call this function from places outside FileBackend and FileOp.
342 * @param array $params
345 final public function nullInternal( array $params ) {
346 return Status
::newGood();
349 final public function concatenate( array $params ) {
350 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
351 $status = Status
::newGood();
353 // Try to lock the source files for the scope of this function
354 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager
::LOCK_UW
, $status );
355 if ( $status->isOK() ) {
356 // Actually do the file concatenation...
357 $start_time = microtime( true );
358 $status->merge( $this->doConcatenate( $params ) );
359 $sec = microtime( true ) - $start_time;
360 if ( !$status->isOK() ) {
361 wfDebugLog( 'FileOperation', get_class( $this ) . "-{$this->name}" .
362 " failed to concatenate " . count( $params['srcs'] ) . " file(s) [$sec sec]" );
370 * @see FileBackendStore::concatenate()
371 * @param array $params
374 protected function doConcatenate( array $params ) {
375 $status = Status
::newGood();
376 $tmpPath = $params['dst']; // convenience
377 unset( $params['latest'] ); // sanity
379 // Check that the specified temp file is valid...
380 MediaWiki\
suppressWarnings();
381 $ok = ( is_file( $tmpPath ) && filesize( $tmpPath ) == 0 );
382 MediaWiki\restoreWarnings
();
383 if ( !$ok ) { // not present or not empty
384 $status->fatal( 'backend-fail-opentemp', $tmpPath );
389 // Get local FS versions of the chunks needed for the concatenation...
390 $fsFiles = $this->getLocalReferenceMulti( $params );
391 foreach ( $fsFiles as $path => &$fsFile ) {
392 if ( !$fsFile ) { // chunk failed to download?
393 $fsFile = $this->getLocalReference( array( 'src' => $path ) );
394 if ( !$fsFile ) { // retry failed?
395 $status->fatal( 'backend-fail-read', $path );
401 unset( $fsFile ); // unset reference so we can reuse $fsFile
403 // Get a handle for the destination temp file
404 $tmpHandle = fopen( $tmpPath, 'ab' );
405 if ( $tmpHandle === false ) {
406 $status->fatal( 'backend-fail-opentemp', $tmpPath );
411 // Build up the temp file using the source chunks (in order)...
412 foreach ( $fsFiles as $virtualSource => $fsFile ) {
413 // Get a handle to the local FS version
414 $sourceHandle = fopen( $fsFile->getPath(), 'rb' );
415 if ( $sourceHandle === false ) {
416 fclose( $tmpHandle );
417 $status->fatal( 'backend-fail-read', $virtualSource );
421 // Append chunk to file (pass chunk size to avoid magic quotes)
422 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
423 fclose( $sourceHandle );
424 fclose( $tmpHandle );
425 $status->fatal( 'backend-fail-writetemp', $tmpPath );
429 fclose( $sourceHandle );
431 if ( !fclose( $tmpHandle ) ) {
432 $status->fatal( 'backend-fail-closetemp', $tmpPath );
437 clearstatcache(); // temp file changed
442 final protected function doPrepare( array $params ) {
443 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
444 $status = Status
::newGood();
446 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
447 if ( $dir === null ) {
448 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
450 return $status; // invalid storage path
453 if ( $shard !== null ) { // confined to a single container/shard
454 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
455 } else { // directory is on several shards
456 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
457 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
458 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
459 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
467 * @see FileBackendStore::doPrepare()
468 * @param string $container
470 * @param array $params
473 protected function doPrepareInternal( $container, $dir, array $params ) {
474 return Status
::newGood();
477 final protected function doSecure( array $params ) {
478 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
479 $status = Status
::newGood();
481 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
482 if ( $dir === null ) {
483 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
485 return $status; // invalid storage path
488 if ( $shard !== null ) { // confined to a single container/shard
489 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
490 } else { // directory is on several shards
491 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
492 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
493 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
494 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
502 * @see FileBackendStore::doSecure()
503 * @param string $container
505 * @param array $params
508 protected function doSecureInternal( $container, $dir, array $params ) {
509 return Status
::newGood();
512 final protected function doPublish( array $params ) {
513 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
514 $status = Status
::newGood();
516 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
517 if ( $dir === null ) {
518 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
520 return $status; // invalid storage path
523 if ( $shard !== null ) { // confined to a single container/shard
524 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
525 } else { // directory is on several shards
526 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
527 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
528 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
529 $status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
537 * @see FileBackendStore::doPublish()
538 * @param string $container
540 * @param array $params
543 protected function doPublishInternal( $container, $dir, array $params ) {
544 return Status
::newGood();
547 final protected function doClean( array $params ) {
548 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
549 $status = Status
::newGood();
551 // Recursive: first delete all empty subdirs recursively
552 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
553 $subDirsRel = $this->getTopDirectoryList( array( 'dir' => $params['dir'] ) );
554 if ( $subDirsRel !== null ) { // no errors
555 foreach ( $subDirsRel as $subDirRel ) {
556 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
557 $status->merge( $this->doClean( array( 'dir' => $subDir ) +
$params ) );
559 unset( $subDirsRel ); // free directory for rmdir() on Windows (for FS backends)
563 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
564 if ( $dir === null ) {
565 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
567 return $status; // invalid storage path
570 // Attempt to lock this directory...
571 $filesLockEx = array( $params['dir'] );
572 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
573 if ( !$status->isOK() ) {
574 return $status; // abort
577 if ( $shard !== null ) { // confined to a single container/shard
578 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
579 $this->deleteContainerCache( $fullCont ); // purge cache
580 } else { // directory is on several shards
581 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
582 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
583 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
584 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
585 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
593 * @see FileBackendStore::doClean()
594 * @param string $container
596 * @param array $params
599 protected function doCleanInternal( $container, $dir, array $params ) {
600 return Status
::newGood();
603 final public function fileExists( array $params ) {
604 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
605 $stat = $this->getFileStat( $params );
607 return ( $stat === null ) ?
null : (bool)$stat; // null => failure
610 final public function getFileTimestamp( array $params ) {
611 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
612 $stat = $this->getFileStat( $params );
614 return $stat ?
$stat['mtime'] : false;
617 final public function getFileSize( array $params ) {
618 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
619 $stat = $this->getFileStat( $params );
621 return $stat ?
$stat['size'] : false;
624 final public function getFileStat( array $params ) {
625 $path = self
::normalizeStoragePath( $params['src'] );
626 if ( $path === null ) {
627 return false; // invalid storage path
629 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
630 $latest = !empty( $params['latest'] ); // use latest data?
631 if ( !$latest && !$this->cheapCache
->has( $path, 'stat', self
::CACHE_TTL
) ) {
632 $this->primeFileCache( array( $path ) ); // check persistent cache
634 if ( $this->cheapCache
->has( $path, 'stat', self
::CACHE_TTL
) ) {
635 $stat = $this->cheapCache
->get( $path, 'stat' );
636 // If we want the latest data, check that this cached
637 // value was in fact fetched with the latest available data.
638 if ( is_array( $stat ) ) {
639 if ( !$latest ||
$stat['latest'] ) {
642 } elseif ( in_array( $stat, array( 'NOT_EXIST', 'NOT_EXIST_LATEST' ) ) ) {
643 if ( !$latest ||
$stat === 'NOT_EXIST_LATEST' ) {
648 $stat = $this->doGetFileStat( $params );
649 if ( is_array( $stat ) ) { // file exists
650 // Strongly consistent backends can automatically set "latest"
651 $stat['latest'] = isset( $stat['latest'] ) ?
$stat['latest'] : $latest;
652 $this->cheapCache
->set( $path, 'stat', $stat );
653 $this->setFileCache( $path, $stat ); // update persistent cache
654 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
655 $this->cheapCache
->set( $path, 'sha1',
656 array( 'hash' => $stat['sha1'], 'latest' => $latest ) );
658 if ( isset( $stat['xattr'] ) ) { // some backends store headers/metadata
659 $stat['xattr'] = self
::normalizeXAttributes( $stat['xattr'] );
660 $this->cheapCache
->set( $path, 'xattr',
661 array( 'map' => $stat['xattr'], 'latest' => $latest ) );
663 } elseif ( $stat === false ) { // file does not exist
664 $this->cheapCache
->set( $path, 'stat', $latest ?
'NOT_EXIST_LATEST' : 'NOT_EXIST' );
665 $this->cheapCache
->set( $path, 'xattr', array( 'map' => false, 'latest' => $latest ) );
666 $this->cheapCache
->set( $path, 'sha1', array( 'hash' => false, 'latest' => $latest ) );
667 wfDebug( __METHOD__
. ": File $path does not exist.\n" );
668 } else { // an error occurred
669 wfDebug( __METHOD__
. ": Could not stat file $path.\n" );
676 * @see FileBackendStore::getFileStat()
678 abstract protected function doGetFileStat( array $params );
680 public function getFileContentsMulti( array $params ) {
681 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
683 $params = $this->setConcurrencyFlags( $params );
684 $contents = $this->doGetFileContentsMulti( $params );
690 * @see FileBackendStore::getFileContentsMulti()
691 * @param array $params
694 protected function doGetFileContentsMulti( array $params ) {
696 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
697 MediaWiki\
suppressWarnings();
698 $contents[$path] = $fsFile ?
file_get_contents( $fsFile->getPath() ) : false;
699 MediaWiki\restoreWarnings
();
705 final public function getFileXAttributes( array $params ) {
706 $path = self
::normalizeStoragePath( $params['src'] );
707 if ( $path === null ) {
708 return false; // invalid storage path
710 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
711 $latest = !empty( $params['latest'] ); // use latest data?
712 if ( $this->cheapCache
->has( $path, 'xattr', self
::CACHE_TTL
) ) {
713 $stat = $this->cheapCache
->get( $path, 'xattr' );
714 // If we want the latest data, check that this cached
715 // value was in fact fetched with the latest available data.
716 if ( !$latest ||
$stat['latest'] ) {
720 $fields = $this->doGetFileXAttributes( $params );
721 $fields = is_array( $fields ) ? self
::normalizeXAttributes( $fields ) : false;
722 $this->cheapCache
->set( $path, 'xattr', array( 'map' => $fields, 'latest' => $latest ) );
728 * @see FileBackendStore::getFileXAttributes()
729 * @return bool|string
731 protected function doGetFileXAttributes( array $params ) {
732 return array( 'headers' => array(), 'metadata' => array() ); // not supported
735 final public function getFileSha1Base36( array $params ) {
736 $path = self
::normalizeStoragePath( $params['src'] );
737 if ( $path === null ) {
738 return false; // invalid storage path
740 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
741 $latest = !empty( $params['latest'] ); // use latest data?
742 if ( $this->cheapCache
->has( $path, 'sha1', self
::CACHE_TTL
) ) {
743 $stat = $this->cheapCache
->get( $path, 'sha1' );
744 // If we want the latest data, check that this cached
745 // value was in fact fetched with the latest available data.
746 if ( !$latest ||
$stat['latest'] ) {
747 return $stat['hash'];
750 $hash = $this->doGetFileSha1Base36( $params );
751 $this->cheapCache
->set( $path, 'sha1', array( 'hash' => $hash, 'latest' => $latest ) );
757 * @see FileBackendStore::getFileSha1Base36()
758 * @param array $params
759 * @return bool|string
761 protected function doGetFileSha1Base36( array $params ) {
762 $fsFile = $this->getLocalReference( $params );
766 return $fsFile->getSha1Base36();
770 final public function getFileProps( array $params ) {
771 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
772 $fsFile = $this->getLocalReference( $params );
773 $props = $fsFile ?
$fsFile->getProps() : FSFile
::placeholderProps();
778 final public function getLocalReferenceMulti( array $params ) {
779 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
781 $params = $this->setConcurrencyFlags( $params );
783 $fsFiles = array(); // (path => FSFile)
784 $latest = !empty( $params['latest'] ); // use latest data?
785 // Reuse any files already in process cache...
786 foreach ( $params['srcs'] as $src ) {
787 $path = self
::normalizeStoragePath( $src );
788 if ( $path === null ) {
789 $fsFiles[$src] = null; // invalid storage path
790 } elseif ( $this->expensiveCache
->has( $path, 'localRef' ) ) {
791 $val = $this->expensiveCache
->get( $path, 'localRef' );
792 // If we want the latest data, check that this cached
793 // value was in fact fetched with the latest available data.
794 if ( !$latest ||
$val['latest'] ) {
795 $fsFiles[$src] = $val['object'];
799 // Fetch local references of any remaning files...
800 $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
801 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
802 $fsFiles[$path] = $fsFile;
803 if ( $fsFile ) { // update the process cache...
804 $this->expensiveCache
->set( $path, 'localRef',
805 array( 'object' => $fsFile, 'latest' => $latest ) );
813 * @see FileBackendStore::getLocalReferenceMulti()
814 * @param array $params
817 protected function doGetLocalReferenceMulti( array $params ) {
818 return $this->doGetLocalCopyMulti( $params );
821 final public function getLocalCopyMulti( array $params ) {
822 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
824 $params = $this->setConcurrencyFlags( $params );
825 $tmpFiles = $this->doGetLocalCopyMulti( $params );
831 * @see FileBackendStore::getLocalCopyMulti()
832 * @param array $params
835 abstract protected function doGetLocalCopyMulti( array $params );
838 * @see FileBackend::getFileHttpUrl()
839 * @param array $params
840 * @return string|null
842 public function getFileHttpUrl( array $params ) {
843 return null; // not supported
846 final public function streamFile( array $params ) {
847 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
848 $status = Status
::newGood();
850 $info = $this->getFileStat( $params );
851 if ( !$info ) { // let StreamFile handle the 404
852 $status->fatal( 'backend-fail-notexists', $params['src'] );
855 // Set output buffer and HTTP headers for stream
856 $extraHeaders = isset( $params['headers'] ) ?
$params['headers'] : array();
857 $res = StreamFile
::prepareForStream( $params['src'], $info, $extraHeaders );
858 if ( $res == StreamFile
::NOT_MODIFIED
) {
859 // do nothing; client cache is up to date
860 } elseif ( $res == StreamFile
::READY_STREAM
) {
861 $status = $this->doStreamFile( $params );
862 if ( !$status->isOK() ) {
863 // Per bug 41113, nasty things can happen if bad cache entries get
864 // stuck in cache. It's also possible that this error can come up
865 // with simple race conditions. Clear out the stat cache to be safe.
866 $this->clearCache( array( $params['src'] ) );
867 $this->deleteFileCache( $params['src'] );
868 trigger_error( "Bad stat cache or race condition for file {$params['src']}." );
871 $status->fatal( 'backend-fail-stream', $params['src'] );
878 * @see FileBackendStore::streamFile()
879 * @param array $params
882 protected function doStreamFile( array $params ) {
883 $status = Status
::newGood();
885 $fsFile = $this->getLocalReference( $params );
887 $status->fatal( 'backend-fail-stream', $params['src'] );
888 } elseif ( !readfile( $fsFile->getPath() ) ) {
889 $status->fatal( 'backend-fail-stream', $params['src'] );
895 final public function directoryExists( array $params ) {
896 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
897 if ( $dir === null ) {
898 return false; // invalid storage path
900 if ( $shard !== null ) { // confined to a single container/shard
901 return $this->doDirectoryExists( $fullCont, $dir, $params );
902 } else { // directory is on several shards
903 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
904 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
905 $res = false; // response
906 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
907 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
911 } elseif ( $exists === null ) { // error?
912 $res = null; // if we don't find anything, it is indeterminate
921 * @see FileBackendStore::directoryExists()
923 * @param string $container Resolved container name
924 * @param string $dir Resolved path relative to container
925 * @param array $params
928 abstract protected function doDirectoryExists( $container, $dir, array $params );
930 final public function getDirectoryList( array $params ) {
931 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
932 if ( $dir === null ) { // invalid storage path
935 if ( $shard !== null ) {
936 // File listing is confined to a single container/shard
937 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
939 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
940 // File listing spans multiple containers/shards
941 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
943 return new FileBackendStoreShardDirIterator( $this,
944 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
949 * Do not call this function from places outside FileBackend
951 * @see FileBackendStore::getDirectoryList()
953 * @param string $container Resolved container name
954 * @param string $dir Resolved path relative to container
955 * @param array $params
956 * @return Traversable|array|null Returns null on failure
958 abstract public function getDirectoryListInternal( $container, $dir, array $params );
960 final public function getFileList( array $params ) {
961 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
962 if ( $dir === null ) { // invalid storage path
965 if ( $shard !== null ) {
966 // File listing is confined to a single container/shard
967 return $this->getFileListInternal( $fullCont, $dir, $params );
969 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
970 // File listing spans multiple containers/shards
971 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
973 return new FileBackendStoreShardFileIterator( $this,
974 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
979 * Do not call this function from places outside FileBackend
981 * @see FileBackendStore::getFileList()
983 * @param string $container Resolved container name
984 * @param string $dir Resolved path relative to container
985 * @param array $params
986 * @return Traversable|array|null Returns null on failure
988 abstract public function getFileListInternal( $container, $dir, array $params );
991 * Return a list of FileOp objects from a list of operations.
992 * Do not call this function from places outside FileBackend.
994 * The result must have the same number of items as the input.
995 * An exception is thrown if an unsupported operation is requested.
997 * @param array $ops Same format as doOperations()
998 * @return array List of FileOp objects
999 * @throws FileBackendError
1001 final public function getOperationsInternal( array $ops ) {
1002 $supportedOps = array(
1003 'store' => 'StoreFileOp',
1004 'copy' => 'CopyFileOp',
1005 'move' => 'MoveFileOp',
1006 'delete' => 'DeleteFileOp',
1007 'create' => 'CreateFileOp',
1008 'describe' => 'DescribeFileOp',
1009 'null' => 'NullFileOp'
1012 $performOps = array(); // array of FileOp objects
1013 // Build up ordered array of FileOps...
1014 foreach ( $ops as $operation ) {
1015 $opName = $operation['op'];
1016 if ( isset( $supportedOps[$opName] ) ) {
1017 $class = $supportedOps[$opName];
1018 // Get params for this operation
1019 $params = $operation;
1020 // Append the FileOp class
1021 $performOps[] = new $class( $this, $params );
1023 throw new FileBackendError( "Operation '$opName' is not supported." );
1031 * Get a list of storage paths to lock for a list of operations
1032 * Returns an array with LockManager::LOCK_UW (shared locks) and
1033 * LockManager::LOCK_EX (exclusive locks) keys, each corresponding
1034 * to a list of storage paths to be locked. All returned paths are
1037 * @param array $performOps List of FileOp objects
1038 * @return array (LockManager::LOCK_UW => path list, LockManager::LOCK_EX => path list)
1040 final public function getPathsToLockForOpsInternal( array $performOps ) {
1041 // Build up a list of files to lock...
1042 $paths = array( 'sh' => array(), 'ex' => array() );
1043 foreach ( $performOps as $fileOp ) {
1044 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1045 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1047 // Optimization: if doing an EX lock anyway, don't also set an SH one
1048 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1049 // Get a shared lock on the parent directory of each path changed
1050 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1053 LockManager
::LOCK_UW
=> $paths['sh'],
1054 LockManager
::LOCK_EX
=> $paths['ex']
1058 public function getScopedLocksForOps( array $ops, Status
$status ) {
1059 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1061 return $this->getScopedFileLocks( $paths, 'mixed', $status );
1064 final protected function doOperationsInternal( array $ops, array $opts ) {
1065 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
1066 $status = Status
::newGood();
1068 // Fix up custom header name/value pairs...
1069 $ops = array_map( array( $this, 'stripInvalidHeadersFromOp' ), $ops );
1071 // Build up a list of FileOps...
1072 $performOps = $this->getOperationsInternal( $ops );
1074 // Acquire any locks as needed...
1075 if ( empty( $opts['nonLocking'] ) ) {
1076 // Build up a list of files to lock...
1077 $paths = $this->getPathsToLockForOpsInternal( $performOps );
1078 // Try to lock those files for the scope of this function...
1080 $scopeLock = $this->getScopedFileLocks( $paths, 'mixed', $status );
1081 if ( !$status->isOK() ) {
1082 return $status; // abort
1086 // Clear any file cache entries (after locks acquired)
1087 if ( empty( $opts['preserveCache'] ) ) {
1088 $this->clearCache();
1091 // Build the list of paths involved
1093 foreach ( $performOps as $op ) {
1094 $paths = array_merge( $paths, $op->storagePathsRead() );
1095 $paths = array_merge( $paths, $op->storagePathsChanged() );
1098 // Enlarge the cache to fit the stat entries of these files
1099 $this->cheapCache
->resize( max( 2 * count( $paths ), self
::CACHE_CHEAP_SIZE
) );
1101 // Load from the persistent container caches
1102 $this->primeContainerCache( $paths );
1103 // Get the latest stat info for all the files (having locked them)
1104 $ok = $this->preloadFileStat( array( 'srcs' => $paths, 'latest' => true ) );
1107 // Actually attempt the operation batch...
1108 $opts = $this->setConcurrencyFlags( $opts );
1109 $subStatus = FileOpBatch
::attempt( $performOps, $opts, $this->fileJournal
);
1111 // If we could not even stat some files, then bail out...
1112 $subStatus = Status
::newFatal( 'backend-fail-internal', $this->name
);
1113 foreach ( $ops as $i => $op ) { // mark each op as failed
1114 $subStatus->success
[$i] = false;
1115 ++
$subStatus->failCount
;
1117 wfDebugLog( 'FileOperation', get_class( $this ) . "-{$this->name} " .
1118 " stat failure; aborted operations: " . FormatJson
::encode( $ops ) );
1121 // Merge errors into status fields
1122 $status->merge( $subStatus );
1123 $status->success
= $subStatus->success
; // not done in merge()
1125 // Shrink the stat cache back to normal size
1126 $this->cheapCache
->resize( self
::CACHE_CHEAP_SIZE
);
1131 final protected function doQuickOperationsInternal( array $ops ) {
1132 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
1133 $status = Status
::newGood();
1135 // Fix up custom header name/value pairs...
1136 $ops = array_map( array( $this, 'stripInvalidHeadersFromOp' ), $ops );
1138 // Clear any file cache entries
1139 $this->clearCache();
1141 $supportedOps = array( 'create', 'store', 'copy', 'move', 'delete', 'describe', 'null' );
1142 // Parallel ops may be disabled in config due to dependencies (e.g. needing popen())
1143 $async = ( $this->parallelize
=== 'implicit' && count( $ops ) > 1 );
1144 $maxConcurrency = $this->concurrency
; // throttle
1146 $statuses = array(); // array of (index => Status)
1147 $fileOpHandles = array(); // list of (index => handle) arrays
1148 $curFileOpHandles = array(); // current handle batch
1149 // Perform the sync-only ops and build up op handles for the async ops...
1150 foreach ( $ops as $index => $params ) {
1151 if ( !in_array( $params['op'], $supportedOps ) ) {
1152 throw new FileBackendError( "Operation '{$params['op']}' is not supported." );
1154 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1155 $subStatus = $this->$method( array( 'async' => $async ) +
$params );
1156 if ( $subStatus->value
instanceof FileBackendStoreOpHandle
) { // async
1157 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1158 $fileOpHandles[] = $curFileOpHandles; // push this batch
1159 $curFileOpHandles = array();
1161 $curFileOpHandles[$index] = $subStatus->value
; // keep index
1162 } else { // error or completed
1163 $statuses[$index] = $subStatus; // keep index
1166 if ( count( $curFileOpHandles ) ) {
1167 $fileOpHandles[] = $curFileOpHandles; // last batch
1169 // Do all the async ops that can be done concurrently...
1170 foreach ( $fileOpHandles as $fileHandleBatch ) {
1171 $statuses = $statuses +
$this->executeOpHandlesInternal( $fileHandleBatch );
1173 // Marshall and merge all the responses...
1174 foreach ( $statuses as $index => $subStatus ) {
1175 $status->merge( $subStatus );
1176 if ( $subStatus->isOK() ) {
1177 $status->success
[$index] = true;
1178 ++
$status->successCount
;
1180 $status->success
[$index] = false;
1181 ++
$status->failCount
;
1189 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1190 * The resulting Status object fields will correspond
1191 * to the order in which the handles where given.
1193 * @param FileBackendStoreOpHandle[] $fileOpHandles
1195 * @throws FileBackendError
1196 * @return array Map of Status objects
1198 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1199 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
1201 foreach ( $fileOpHandles as $fileOpHandle ) {
1202 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle
) ) {
1203 throw new FileBackendError( "Given a non-FileBackendStoreOpHandle object." );
1204 } elseif ( $fileOpHandle->backend
->getName() !== $this->getName() ) {
1205 throw new FileBackendError( "Given a FileBackendStoreOpHandle for the wrong backend." );
1208 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1209 foreach ( $fileOpHandles as $fileOpHandle ) {
1210 $fileOpHandle->closeResources();
1217 * @see FileBackendStore::executeOpHandlesInternal()
1219 * @param FileBackendStoreOpHandle[] $fileOpHandles
1221 * @throws FileBackendError
1222 * @return Status[] List of corresponding Status objects
1224 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1225 if ( count( $fileOpHandles ) ) {
1226 throw new FileBackendError( "This backend supports no asynchronous operations." );
1233 * Strip long HTTP headers from a file operation.
1234 * Most headers are just numbers, but some are allowed to be long.
1235 * This function is useful for cleaning up headers and avoiding backend
1236 * specific errors, especially in the middle of batch file operations.
1238 * @param array $op Same format as doOperation()
1241 protected function stripInvalidHeadersFromOp( array $op ) {
1242 static $longs = array( 'Content-Disposition' );
1243 if ( isset( $op['headers'] ) ) { // op sets HTTP headers
1244 foreach ( $op['headers'] as $name => $value ) {
1245 $maxHVLen = in_array( $name, $longs ) ? INF
: 255;
1246 if ( strlen( $name ) > 255 ||
strlen( $value ) > $maxHVLen ) {
1247 trigger_error( "Header '$name: $value' is too long." );
1248 unset( $op['headers'][$name] );
1249 } elseif ( !strlen( $value ) ) {
1250 $op['headers'][$name] = ''; // null/false => ""
1258 final public function preloadCache( array $paths ) {
1259 $fullConts = array(); // full container names
1260 foreach ( $paths as $path ) {
1261 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1262 $fullConts[] = $fullCont;
1264 // Load from the persistent file and container caches
1265 $this->primeContainerCache( $fullConts );
1266 $this->primeFileCache( $paths );
1269 final public function clearCache( array $paths = null ) {
1270 if ( is_array( $paths ) ) {
1271 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1272 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1274 if ( $paths === null ) {
1275 $this->cheapCache
->clear();
1276 $this->expensiveCache
->clear();
1278 foreach ( $paths as $path ) {
1279 $this->cheapCache
->clear( $path );
1280 $this->expensiveCache
->clear( $path );
1283 $this->doClearCache( $paths );
1287 * Clears any additional stat caches for storage paths
1289 * @see FileBackend::clearCache()
1291 * @param array $paths Storage paths (optional)
1293 protected function doClearCache( array $paths = null ) {
1296 final public function preloadFileStat( array $params ) {
1297 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
1298 $success = true; // no network errors
1300 $params['concurrency'] = ( $this->parallelize
!== 'off' ) ?
$this->concurrency
: 1;
1301 $stats = $this->doGetFileStatMulti( $params );
1302 if ( $stats === null ) {
1303 return true; // not supported
1306 $latest = !empty( $params['latest'] ); // use latest data?
1307 foreach ( $stats as $path => $stat ) {
1308 $path = FileBackend
::normalizeStoragePath( $path );
1309 if ( $path === null ) {
1310 continue; // this shouldn't happen
1312 if ( is_array( $stat ) ) { // file exists
1313 // Strongly consistent backends can automatically set "latest"
1314 $stat['latest'] = isset( $stat['latest'] ) ?
$stat['latest'] : $latest;
1315 $this->cheapCache
->set( $path, 'stat', $stat );
1316 $this->setFileCache( $path, $stat ); // update persistent cache
1317 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
1318 $this->cheapCache
->set( $path, 'sha1',
1319 array( 'hash' => $stat['sha1'], 'latest' => $latest ) );
1321 if ( isset( $stat['xattr'] ) ) { // some backends store headers/metadata
1322 $stat['xattr'] = self
::normalizeXAttributes( $stat['xattr'] );
1323 $this->cheapCache
->set( $path, 'xattr',
1324 array( 'map' => $stat['xattr'], 'latest' => $latest ) );
1326 } elseif ( $stat === false ) { // file does not exist
1327 $this->cheapCache
->set( $path, 'stat',
1328 $latest ?
'NOT_EXIST_LATEST' : 'NOT_EXIST' );
1329 $this->cheapCache
->set( $path, 'xattr',
1330 array( 'map' => false, 'latest' => $latest ) );
1331 $this->cheapCache
->set( $path, 'sha1',
1332 array( 'hash' => false, 'latest' => $latest ) );
1333 wfDebug( __METHOD__
. ": File $path does not exist.\n" );
1334 } else { // an error occurred
1336 wfDebug( __METHOD__
. ": Could not stat file $path.\n" );
1344 * Get file stat information (concurrently if possible) for several files
1346 * @see FileBackend::getFileStat()
1348 * @param array $params Parameters include:
1349 * - srcs : list of source storage paths
1350 * - latest : use the latest available data
1351 * @return array|null Map of storage paths to array|bool|null (returns null if not supported)
1354 protected function doGetFileStatMulti( array $params ) {
1355 return null; // not supported
1359 * Is this a key/value store where directories are just virtual?
1360 * Virtual directories exists in so much as files exists that are
1361 * prefixed with the directory path followed by a forward slash.
1365 abstract protected function directoriesAreVirtual();
1368 * Check if a short container name is valid
1370 * This checks for length and illegal characters.
1371 * This may disallow certain characters that can appear
1372 * in the prefix used to make the full container name.
1374 * @param string $container
1377 final protected static function isValidShortContainerName( $container ) {
1378 // Suffixes like '.xxx' (hex shard chars) or '.seg' (file segments)
1379 // might be used by subclasses. Reserve the dot character for sanity.
1380 // The only way dots end up in containers (e.g. resolveStoragePath)
1381 // is due to the wikiId container prefix or the above suffixes.
1382 return self
::isValidContainerName( $container ) && !preg_match( '/[.]/', $container );
1386 * Check if a full container name is valid
1388 * This checks for length and illegal characters.
1389 * Limiting the characters makes migrations to other stores easier.
1391 * @param string $container
1394 final protected static function isValidContainerName( $container ) {
1395 // This accounts for NTFS, Swift, and Ceph restrictions
1396 // and disallows directory separators or traversal characters.
1397 // Note that matching strings URL encode to the same string;
1398 // in Swift/Ceph, the length restriction is *after* URL encoding.
1399 return (bool)preg_match( '/^[a-z0-9][a-z0-9-_.]{0,199}$/i', $container );
1403 * Splits a storage path into an internal container name,
1404 * an internal relative file name, and a container shard suffix.
1405 * Any shard suffix is already appended to the internal container name.
1406 * This also checks that the storage path is valid and within this backend.
1408 * If the container is sharded but a suffix could not be determined,
1409 * this means that the path can only refer to a directory and can only
1410 * be scanned by looking in all the container shards.
1412 * @param string $storagePath
1413 * @return array (container, path, container suffix) or (null, null, null) if invalid
1415 final protected function resolveStoragePath( $storagePath ) {
1416 list( $backend, $shortCont, $relPath ) = self
::splitStoragePath( $storagePath );
1417 if ( $backend === $this->name
) { // must be for this backend
1418 $relPath = self
::normalizeContainerPath( $relPath );
1419 if ( $relPath !== null && self
::isValidShortContainerName( $shortCont ) ) {
1420 // Get shard for the normalized path if this container is sharded
1421 $cShard = $this->getContainerShard( $shortCont, $relPath );
1422 // Validate and sanitize the relative path (backend-specific)
1423 $relPath = $this->resolveContainerPath( $shortCont, $relPath );
1424 if ( $relPath !== null ) {
1425 // Prepend any wiki ID prefix to the container name
1426 $container = $this->fullContainerName( $shortCont );
1427 if ( self
::isValidContainerName( $container ) ) {
1428 // Validate and sanitize the container name (backend-specific)
1429 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1430 if ( $container !== null ) {
1431 return array( $container, $relPath, $cShard );
1438 return array( null, null, null );
1442 * Like resolveStoragePath() except null values are returned if
1443 * the container is sharded and the shard could not be determined
1444 * or if the path ends with '/'. The later case is illegal for FS
1445 * backends and can confuse listings for object store backends.
1447 * This function is used when resolving paths that must be valid
1448 * locations for files. Directory and listing functions should
1449 * generally just use resolveStoragePath() instead.
1451 * @see FileBackendStore::resolveStoragePath()
1453 * @param string $storagePath
1454 * @return array (container, path) or (null, null) if invalid
1456 final protected function resolveStoragePathReal( $storagePath ) {
1457 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1458 if ( $cShard !== null && substr( $relPath, -1 ) !== '/' ) {
1459 return array( $container, $relPath );
1462 return array( null, null );
1466 * Get the container name shard suffix for a given path.
1467 * Any empty suffix means the container is not sharded.
1469 * @param string $container Container name
1470 * @param string $relPath Storage path relative to the container
1471 * @return string|null Returns null if shard could not be determined
1473 final protected function getContainerShard( $container, $relPath ) {
1474 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1475 if ( $levels == 1 ||
$levels == 2 ) {
1476 // Hash characters are either base 16 or 36
1477 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1478 // Get a regex that represents the shard portion of paths.
1479 // The concatenation of the captures gives us the shard.
1480 if ( $levels === 1 ) { // 16 or 36 shards per container
1481 $hashDirRegex = '(' . $char . ')';
1482 } else { // 256 or 1296 shards per container
1483 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1484 $hashDirRegex = $char . '/(' . $char . '{2})';
1485 } else { // short hash dir format (e.g. "a/b/c")
1486 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1489 // Allow certain directories to be above the hash dirs so as
1490 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1491 // They must be 2+ chars to avoid any hash directory ambiguity.
1493 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1494 return '.' . implode( '', array_slice( $m, 1 ) );
1497 return null; // failed to match
1500 return ''; // no sharding
1504 * Check if a storage path maps to a single shard.
1505 * Container dirs like "a", where the container shards on "x/xy",
1506 * can reside on several shards. Such paths are tricky to handle.
1508 * @param string $storagePath Storage path
1511 final public function isSingleShardPathInternal( $storagePath ) {
1512 list( , , $shard ) = $this->resolveStoragePath( $storagePath );
1514 return ( $shard !== null );
1518 * Get the sharding config for a container.
1519 * If greater than 0, then all file storage paths within
1520 * the container are required to be hashed accordingly.
1522 * @param string $container
1523 * @return array (integer levels, integer base, repeat flag) or (0, 0, false)
1525 final protected function getContainerHashLevels( $container ) {
1526 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1527 $config = $this->shardViaHashLevels
[$container];
1528 $hashLevels = (int)$config['levels'];
1529 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1530 $hashBase = (int)$config['base'];
1531 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1532 return array( $hashLevels, $hashBase, $config['repeat'] );
1537 return array( 0, 0, false ); // no sharding
1541 * Get a list of full container shard suffixes for a container
1543 * @param string $container
1546 final protected function getContainerSuffixes( $container ) {
1548 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1549 if ( $digits > 0 ) {
1550 $numShards = pow( $base, $digits );
1551 for ( $index = 0; $index < $numShards; $index++
) {
1552 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1560 * Get the full container name, including the wiki ID prefix
1562 * @param string $container
1565 final protected function fullContainerName( $container ) {
1566 if ( $this->wikiId
!= '' ) {
1567 return "{$this->wikiId}-$container";
1574 * Resolve a container name, checking if it's allowed by the backend.
1575 * This is intended for internal use, such as encoding illegal chars.
1576 * Subclasses can override this to be more restrictive.
1578 * @param string $container
1579 * @return string|null
1581 protected function resolveContainerName( $container ) {
1586 * Resolve a relative storage path, checking if it's allowed by the backend.
1587 * This is intended for internal use, such as encoding illegal chars or perhaps
1588 * getting absolute paths (e.g. FS based backends). Note that the relative path
1589 * may be the empty string (e.g. the path is simply to the container).
1591 * @param string $container Container name
1592 * @param string $relStoragePath Storage path relative to the container
1593 * @return string|null Path or null if not valid
1595 protected function resolveContainerPath( $container, $relStoragePath ) {
1596 return $relStoragePath;
1600 * Get the cache key for a container
1602 * @param string $container Resolved container name
1605 private function containerCacheKey( $container ) {
1606 return "filebackend:{$this->name}:{$this->wikiId}:container:{$container}";
1610 * Set the cached info for a container
1612 * @param string $container Resolved container name
1613 * @param array $val Information to cache
1615 final protected function setContainerCache( $container, array $val ) {
1616 $this->memCache
->set( $this->containerCacheKey( $container ), $val, 14 * 86400 );
1620 * Delete the cached info for a container.
1621 * The cache key is salted for a while to prevent race conditions.
1623 * @param string $container Resolved container name
1625 final protected function deleteContainerCache( $container ) {
1626 if ( !$this->memCache
->delete( $this->containerCacheKey( $container ), 300 ) ) {
1627 trigger_error( "Unable to delete stat cache for container $container." );
1632 * Do a batch lookup from cache for container stats for all containers
1633 * used in a list of container names or storage paths objects.
1634 * This loads the persistent cache values into the process cache.
1636 * @param array $items
1638 final protected function primeContainerCache( array $items ) {
1639 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
1641 $paths = array(); // list of storage paths
1642 $contNames = array(); // (cache key => resolved container name)
1643 // Get all the paths/containers from the items...
1644 foreach ( $items as $item ) {
1645 if ( self
::isStoragePath( $item ) ) {
1647 } elseif ( is_string( $item ) ) { // full container name
1648 $contNames[$this->containerCacheKey( $item )] = $item;
1651 // Get all the corresponding cache keys for paths...
1652 foreach ( $paths as $path ) {
1653 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1654 if ( $fullCont !== null ) { // valid path for this backend
1655 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1659 $contInfo = array(); // (resolved container name => cache value)
1660 // Get all cache entries for these container cache keys...
1661 $values = $this->memCache
->getMulti( array_keys( $contNames ) );
1662 foreach ( $values as $cacheKey => $val ) {
1663 $contInfo[$contNames[$cacheKey]] = $val;
1666 // Populate the container process cache for the backend...
1667 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1671 * Fill the backend-specific process cache given an array of
1672 * resolved container names and their corresponding cached info.
1673 * Only containers that actually exist should appear in the map.
1675 * @param array $containerInfo Map of resolved container names to cached info
1677 protected function doPrimeContainerCache( array $containerInfo ) {
1681 * Get the cache key for a file path
1683 * @param string $path Normalized storage path
1686 private function fileCacheKey( $path ) {
1687 return "filebackend:{$this->name}:{$this->wikiId}:file:" . sha1( $path );
1691 * Set the cached stat info for a file path.
1692 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1693 * salting for the case when a file is created at a path were there was none before.
1695 * @param string $path Storage path
1696 * @param array $val Stat information to cache
1698 final protected function setFileCache( $path, array $val ) {
1699 $path = FileBackend
::normalizeStoragePath( $path );
1700 if ( $path === null ) {
1701 return; // invalid storage path
1703 $age = time() - wfTimestamp( TS_UNIX
, $val['mtime'] );
1704 $ttl = min( 7 * 86400, max( 300, floor( .1 * $age ) ) );
1705 $key = $this->fileCacheKey( $path );
1706 // Set the cache unless it is currently salted.
1707 $this->memCache
->set( $key, $val, $ttl );
1711 * Delete the cached stat info for a file path.
1712 * The cache key is salted for a while to prevent race conditions.
1713 * Since negatives (404s) are not cached, this does not need to be called when
1714 * a file is created at a path were there was none before.
1716 * @param string $path Storage path
1718 final protected function deleteFileCache( $path ) {
1719 $path = FileBackend
::normalizeStoragePath( $path );
1720 if ( $path === null ) {
1721 return; // invalid storage path
1723 if ( !$this->memCache
->delete( $this->fileCacheKey( $path ), 300 ) ) {
1724 trigger_error( "Unable to delete stat cache for file $path." );
1729 * Do a batch lookup from cache for file stats for all paths
1730 * used in a list of storage paths or FileOp objects.
1731 * This loads the persistent cache values into the process cache.
1733 * @param array $items List of storage paths
1735 final protected function primeFileCache( array $items ) {
1736 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
1738 $paths = array(); // list of storage paths
1739 $pathNames = array(); // (cache key => storage path)
1740 // Get all the paths/containers from the items...
1741 foreach ( $items as $item ) {
1742 if ( self
::isStoragePath( $item ) ) {
1743 $paths[] = FileBackend
::normalizeStoragePath( $item );
1746 // Get rid of any paths that failed normalization...
1747 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1748 // Get all the corresponding cache keys for paths...
1749 foreach ( $paths as $path ) {
1750 list( , $rel, ) = $this->resolveStoragePath( $path );
1751 if ( $rel !== null ) { // valid path for this backend
1752 $pathNames[$this->fileCacheKey( $path )] = $path;
1755 // Get all cache entries for these file cache keys...
1756 $values = $this->memCache
->getMulti( array_keys( $pathNames ) );
1757 foreach ( $values as $cacheKey => $val ) {
1758 $path = $pathNames[$cacheKey];
1759 if ( is_array( $val ) ) {
1760 $val['latest'] = false; // never completely trust cache
1761 $this->cheapCache
->set( $path, 'stat', $val );
1762 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1763 $this->cheapCache
->set( $path, 'sha1',
1764 array( 'hash' => $val['sha1'], 'latest' => false ) );
1766 if ( isset( $val['xattr'] ) ) { // some backends store headers/metadata
1767 $val['xattr'] = self
::normalizeXAttributes( $val['xattr'] );
1768 $this->cheapCache
->set( $path, 'xattr',
1769 array( 'map' => $val['xattr'], 'latest' => false ) );
1776 * Normalize file headers/metadata to the FileBackend::getFileXAttributes() format
1778 * @param array $xattr
1782 final protected static function normalizeXAttributes( array $xattr ) {
1783 $newXAttr = array( 'headers' => array(), 'metadata' => array() );
1785 foreach ( $xattr['headers'] as $name => $value ) {
1786 $newXAttr['headers'][strtolower( $name )] = $value;
1789 foreach ( $xattr['metadata'] as $name => $value ) {
1790 $newXAttr['metadata'][strtolower( $name )] = $value;
1797 * Set the 'concurrency' option from a list of operation options
1799 * @param array $opts Map of operation options
1802 final protected function setConcurrencyFlags( array $opts ) {
1803 $opts['concurrency'] = 1; // off
1804 if ( $this->parallelize
=== 'implicit' ) {
1805 if ( !isset( $opts['parallelize'] ) ||
$opts['parallelize'] ) {
1806 $opts['concurrency'] = $this->concurrency
;
1808 } elseif ( $this->parallelize
=== 'explicit' ) {
1809 if ( !empty( $opts['parallelize'] ) ) {
1810 $opts['concurrency'] = $this->concurrency
;
1818 * Get the content type to use in HEAD/GET requests for a file
1820 * @param string $storagePath
1821 * @param string|null $content File data
1822 * @param string|null $fsPath File system path
1823 * @return string MIME type
1825 protected function getContentType( $storagePath, $content, $fsPath ) {
1826 return call_user_func_array( $this->mimeCallback
, func_get_args() );
1831 * FileBackendStore helper class for performing asynchronous file operations.
1833 * For example, calling FileBackendStore::createInternal() with the "async"
1834 * param flag may result in a Status that contains this object as a value.
1835 * This class is largely backend-specific and is mostly just "magic" to be
1836 * passed to FileBackendStore::executeOpHandlesInternal().
1838 abstract class FileBackendStoreOpHandle
{
1840 public $params = array(); // params to caller functions
1841 /** @var FileBackendStore */
1844 public $resourcesToClose = array();
1846 public $call; // string; name that identifies the function called
1849 * Close all open file handles
1851 public function closeResources() {
1852 array_map( 'fclose', $this->resourcesToClose
);
1857 * FileBackendStore helper function to handle listings that span container shards.
1858 * Do not use this class from places outside of FileBackendStore.
1860 * @ingroup FileBackend
1862 abstract class FileBackendStoreShardListIterator
extends FilterIterator
{
1863 /** @var FileBackendStore */
1869 /** @var string Full container name */
1870 protected $container;
1872 /** @var string Resolved relative path */
1873 protected $directory;
1876 protected $multiShardPaths = array(); // (rel path => 1)
1879 * @param FileBackendStore $backend
1880 * @param string $container Full storage container name
1881 * @param string $dir Storage directory relative to container
1882 * @param array $suffixes List of container shard suffixes
1883 * @param array $params
1885 public function __construct(
1886 FileBackendStore
$backend, $container, $dir, array $suffixes, array $params
1888 $this->backend
= $backend;
1889 $this->container
= $container;
1890 $this->directory
= $dir;
1891 $this->params
= $params;
1893 $iter = new AppendIterator();
1894 foreach ( $suffixes as $suffix ) {
1895 $iter->append( $this->listFromShard( $this->container
. $suffix ) );
1898 parent
::__construct( $iter );
1901 public function accept() {
1902 $rel = $this->getInnerIterator()->current(); // path relative to given directory
1903 $path = $this->params
['dir'] . "/{$rel}"; // full storage path
1904 if ( $this->backend
->isSingleShardPathInternal( $path ) ) {
1905 return true; // path is only on one shard; no issue with duplicates
1906 } elseif ( isset( $this->multiShardPaths
[$rel] ) ) {
1907 // Don't keep listing paths that are on multiple shards
1910 $this->multiShardPaths
[$rel] = 1;
1916 public function rewind() {
1918 $this->multiShardPaths
= array();
1922 * Get the list for a given container shard
1924 * @param string $container Resolved container name
1927 abstract protected function listFromShard( $container );
1931 * Iterator for listing directories
1933 class FileBackendStoreShardDirIterator
extends FileBackendStoreShardListIterator
{
1934 protected function listFromShard( $container ) {
1935 $list = $this->backend
->getDirectoryListInternal(
1936 $container, $this->directory
, $this->params
);
1937 if ( $list === null ) {
1938 return new ArrayIterator( array() );
1940 return is_array( $list ) ?
new ArrayIterator( $list ) : $list;
1946 * Iterator for listing regular files
1948 class FileBackendStoreShardFileIterator
extends FileBackendStoreShardListIterator
{
1949 protected function listFromShard( $container ) {
1950 $list = $this->backend
->getFileListInternal(
1951 $container, $this->directory
, $this->params
);
1952 if ( $list === null ) {
1953 return new ArrayIterator( array() );
1955 return is_array( $list ) ?
new ArrayIterator( $list ) : $list;