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
{
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 callback 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 * - mimeCallback : Callback that takes (storage path, content, file system path) and
62 * returns the MIME type of the file or 'unknown/unknown'. The file
63 * system path parameter should be used if the content one is null.
65 * @param array $config
67 public function __construct( array $config ) {
68 parent
::__construct( $config );
69 $this->mimeCallback
= isset( $config['mimeCallback'] )
70 ?
$config['mimeCallback']
71 : function ( $storagePath, $content, $fsPath ) {
72 // @TODO: handle the case of extension-less files using the contents
73 return StreamFile
::contentTypeFromPath( $storagePath ) ?
: 'unknown/unknown';
75 $this->memCache
= new EmptyBagOStuff(); // disabled by default
76 $this->cheapCache
= new ProcessCacheLRU( self
::CACHE_CHEAP_SIZE
);
77 $this->expensiveCache
= new ProcessCacheLRU( self
::CACHE_EXPENSIVE_SIZE
);
81 * Get the maximum allowable file size given backend
82 * medium restrictions and basic performance constraints.
83 * Do not call this function from places outside FileBackend and FileOp.
87 final public function maxFileSizeInternal() {
88 return $this->maxFileSize
;
92 * Check if a file can be created or changed at a given storage path.
93 * FS backends should check if the parent directory exists, files can be
94 * written under it, and that any file already there is writable.
95 * Backends using key/value stores should check if the container exists.
97 * @param string $storagePath
100 abstract public function isPathUsableInternal( $storagePath );
103 * Create a file in the backend with the given contents.
104 * This will overwrite any file that exists at the destination.
105 * Do not call this function from places outside FileBackend and FileOp.
108 * - content : the raw file contents
109 * - dst : destination storage path
110 * - headers : HTTP header name/value map
111 * - async : Status will be returned immediately if supported.
112 * If the status is OK, then its value field will be
113 * set to a FileBackendStoreOpHandle object.
114 * - dstExists : Whether a file exists at the destination (optimization).
115 * Callers can use "false" if no existing file is being changed.
117 * @param array $params
120 final public function createInternal( array $params ) {
121 $section = new ProfileSection( __METHOD__
. "-{$this->name}" );
122 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
123 $status = Status
::newFatal( 'backend-fail-maxsize',
124 $params['dst'], $this->maxFileSizeInternal() );
126 $status = $this->doCreateInternal( $params );
127 $this->clearCache( array( $params['dst'] ) );
128 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
129 $this->deleteFileCache( $params['dst'] ); // persistent cache
137 * @see FileBackendStore::createInternal()
138 * @param array $params
141 abstract protected function doCreateInternal( array $params );
144 * Store a file into the backend from a file on disk.
145 * This will overwrite any file that exists at the destination.
146 * Do not call this function from places outside FileBackend and FileOp.
149 * - src : source path on disk
150 * - dst : destination storage path
151 * - headers : HTTP header name/value map
152 * - async : Status will be returned immediately if supported.
153 * If the status is OK, then its value field will be
154 * set to a FileBackendStoreOpHandle object.
155 * - dstExists : Whether a file exists at the destination (optimization).
156 * Callers can use "false" if no existing file is being changed.
158 * @param array $params
161 final public function storeInternal( array $params ) {
162 $section = new ProfileSection( __METHOD__
. "-{$this->name}" );
163 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
164 $status = Status
::newFatal( 'backend-fail-maxsize',
165 $params['dst'], $this->maxFileSizeInternal() );
167 $status = $this->doStoreInternal( $params );
168 $this->clearCache( array( $params['dst'] ) );
169 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
170 $this->deleteFileCache( $params['dst'] ); // persistent cache
178 * @see FileBackendStore::storeInternal()
179 * @param array $params
182 abstract protected function doStoreInternal( array $params );
185 * Copy a file from one storage path to another in the backend.
186 * This will overwrite any file that exists at the destination.
187 * Do not call this function from places outside FileBackend and FileOp.
190 * - src : source storage path
191 * - dst : destination storage path
192 * - ignoreMissingSource : do nothing if the source file does not exist
193 * - headers : HTTP header name/value map
194 * - async : Status will be returned immediately if supported.
195 * If the status is OK, then its value field will be
196 * set to a FileBackendStoreOpHandle object.
197 * - dstExists : Whether a file exists at the destination (optimization).
198 * Callers can use "false" if no existing file is being changed.
200 * @param array $params
203 final public function copyInternal( array $params ) {
204 $section = new ProfileSection( __METHOD__
. "-{$this->name}" );
205 $status = $this->doCopyInternal( $params );
206 $this->clearCache( array( $params['dst'] ) );
207 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
208 $this->deleteFileCache( $params['dst'] ); // persistent cache
215 * @see FileBackendStore::copyInternal()
216 * @param array $params
219 abstract protected function doCopyInternal( array $params );
222 * Delete a file at the storage path.
223 * Do not call this function from places outside FileBackend and FileOp.
226 * - src : source storage path
227 * - ignoreMissingSource : do nothing if the source file does not exist
228 * - async : Status will be returned immediately if supported.
229 * If the status is OK, then its value field will be
230 * set to a FileBackendStoreOpHandle object.
232 * @param array $params
235 final public function deleteInternal( array $params ) {
236 $section = new ProfileSection( __METHOD__
. "-{$this->name}" );
237 $status = $this->doDeleteInternal( $params );
238 $this->clearCache( array( $params['src'] ) );
239 $this->deleteFileCache( $params['src'] ); // persistent cache
244 * @see FileBackendStore::deleteInternal()
245 * @param array $params
248 abstract protected function doDeleteInternal( array $params );
251 * Move a file from one storage path to another in the backend.
252 * This will overwrite any file that exists at the destination.
253 * Do not call this function from places outside FileBackend and FileOp.
256 * - src : source storage path
257 * - dst : destination storage path
258 * - ignoreMissingSource : do nothing if the source file does not exist
259 * - headers : HTTP header name/value map
260 * - async : Status will be returned immediately if supported.
261 * If the status is OK, then its value field will be
262 * set to a FileBackendStoreOpHandle object.
263 * - dstExists : Whether a file exists at the destination (optimization).
264 * Callers can use "false" if no existing file is being changed.
266 * @param array $params
269 final public function moveInternal( array $params ) {
270 $section = new ProfileSection( __METHOD__
. "-{$this->name}" );
271 $status = $this->doMoveInternal( $params );
272 $this->clearCache( array( $params['src'], $params['dst'] ) );
273 $this->deleteFileCache( $params['src'] ); // persistent cache
274 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
275 $this->deleteFileCache( $params['dst'] ); // persistent cache
282 * @see FileBackendStore::moveInternal()
283 * @param array $params
286 protected function doMoveInternal( array $params ) {
287 unset( $params['async'] ); // two steps, won't work here :)
288 $nsrc = FileBackend
::normalizeStoragePath( $params['src'] );
289 $ndst = FileBackend
::normalizeStoragePath( $params['dst'] );
290 // Copy source to dest
291 $status = $this->copyInternal( $params );
292 if ( $nsrc !== $ndst && $status->isOK() ) {
293 // Delete source (only fails due to races or network problems)
294 $status->merge( $this->deleteInternal( array( 'src' => $params['src'] ) ) );
295 $status->setResult( true, $status->value
); // ignore delete() errors
302 * Alter metadata for a file at the storage path.
303 * Do not call this function from places outside FileBackend and FileOp.
306 * - src : source storage path
307 * - headers : HTTP header name/value map
308 * - async : Status will be returned immediately if supported.
309 * If the status is OK, then its value field will be
310 * set to a FileBackendStoreOpHandle object.
312 * @param array $params
315 final public function describeInternal( array $params ) {
316 $section = new ProfileSection( __METHOD__
. "-{$this->name}" );
317 if ( count( $params['headers'] ) ) {
318 $status = $this->doDescribeInternal( $params );
319 $this->clearCache( array( $params['src'] ) );
320 $this->deleteFileCache( $params['src'] ); // persistent cache
322 $status = Status
::newGood(); // nothing to do
329 * @see FileBackendStore::describeInternal()
330 * @param array $params
333 protected function doDescribeInternal( array $params ) {
334 return Status
::newGood();
338 * No-op file operation that does nothing.
339 * Do not call this function from places outside FileBackend and FileOp.
341 * @param array $params
344 final public function nullInternal( array $params ) {
345 return Status
::newGood();
348 final public function concatenate( array $params ) {
349 $section = new ProfileSection( __METHOD__
. "-{$this->name}" );
350 $status = Status
::newGood();
352 // Try to lock the source files for the scope of this function
353 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager
::LOCK_UW
, $status );
354 if ( $status->isOK() ) {
355 // Actually do the file concatenation...
356 $start_time = microtime( true );
357 $status->merge( $this->doConcatenate( $params ) );
358 $sec = microtime( true ) - $start_time;
359 if ( !$status->isOK() ) {
360 wfDebugLog( 'FileOperation', get_class( $this ) . " failed to concatenate " .
361 count( $params['srcs'] ) . " file(s) [$sec sec]" );
369 * @see FileBackendStore::concatenate()
370 * @param array $params
373 protected function doConcatenate( array $params ) {
374 $status = Status
::newGood();
375 $tmpPath = $params['dst']; // convenience
376 unset( $params['latest'] ); // sanity
378 // Check that the specified temp file is valid...
379 wfSuppressWarnings();
380 $ok = ( is_file( $tmpPath ) && filesize( $tmpPath ) == 0 );
382 if ( !$ok ) { // not present or not empty
383 $status->fatal( 'backend-fail-opentemp', $tmpPath );
388 // Get local FS versions of the chunks needed for the concatenation...
389 $fsFiles = $this->getLocalReferenceMulti( $params );
390 foreach ( $fsFiles as $path => &$fsFile ) {
391 if ( !$fsFile ) { // chunk failed to download?
392 $fsFile = $this->getLocalReference( array( 'src' => $path ) );
393 if ( !$fsFile ) { // retry failed?
394 $status->fatal( 'backend-fail-read', $path );
400 unset( $fsFile ); // unset reference so we can reuse $fsFile
402 // Get a handle for the destination temp file
403 $tmpHandle = fopen( $tmpPath, 'ab' );
404 if ( $tmpHandle === false ) {
405 $status->fatal( 'backend-fail-opentemp', $tmpPath );
410 // Build up the temp file using the source chunks (in order)...
411 foreach ( $fsFiles as $virtualSource => $fsFile ) {
412 // Get a handle to the local FS version
413 $sourceHandle = fopen( $fsFile->getPath(), 'rb' );
414 if ( $sourceHandle === false ) {
415 fclose( $tmpHandle );
416 $status->fatal( 'backend-fail-read', $virtualSource );
420 // Append chunk to file (pass chunk size to avoid magic quotes)
421 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
422 fclose( $sourceHandle );
423 fclose( $tmpHandle );
424 $status->fatal( 'backend-fail-writetemp', $tmpPath );
428 fclose( $sourceHandle );
430 if ( !fclose( $tmpHandle ) ) {
431 $status->fatal( 'backend-fail-closetemp', $tmpPath );
436 clearstatcache(); // temp file changed
441 final protected function doPrepare( array $params ) {
442 $section = new ProfileSection( __METHOD__
. "-{$this->name}" );
443 $status = Status
::newGood();
445 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
446 if ( $dir === null ) {
447 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
449 return $status; // invalid storage path
452 if ( $shard !== null ) { // confined to a single container/shard
453 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
454 } else { // directory is on several shards
455 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
456 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
457 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
458 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
466 * @see FileBackendStore::doPrepare()
469 * @param array $params
472 protected function doPrepareInternal( $container, $dir, array $params ) {
473 return Status
::newGood();
476 final protected function doSecure( array $params ) {
477 $section = new ProfileSection( __METHOD__
. "-{$this->name}" );
478 $status = Status
::newGood();
480 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
481 if ( $dir === null ) {
482 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
484 return $status; // invalid storage path
487 if ( $shard !== null ) { // confined to a single container/shard
488 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
489 } else { // directory is on several shards
490 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
491 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
492 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
493 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
501 * @see FileBackendStore::doSecure()
504 * @param array $params
507 protected function doSecureInternal( $container, $dir, array $params ) {
508 return Status
::newGood();
511 final protected function doPublish( array $params ) {
512 $section = new ProfileSection( __METHOD__
. "-{$this->name}" );
513 $status = Status
::newGood();
515 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
516 if ( $dir === null ) {
517 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
519 return $status; // invalid storage path
522 if ( $shard !== null ) { // confined to a single container/shard
523 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
524 } else { // directory is on several shards
525 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
526 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
527 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
528 $status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
536 * @see FileBackendStore::doPublish()
539 * @param array $params
542 protected function doPublishInternal( $container, $dir, array $params ) {
543 return Status
::newGood();
546 final protected function doClean( array $params ) {
547 $section = new ProfileSection( __METHOD__
. "-{$this->name}" );
548 $status = Status
::newGood();
550 // Recursive: first delete all empty subdirs recursively
551 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
552 $subDirsRel = $this->getTopDirectoryList( array( 'dir' => $params['dir'] ) );
553 if ( $subDirsRel !== null ) { // no errors
554 foreach ( $subDirsRel as $subDirRel ) {
555 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
556 $status->merge( $this->doClean( array( 'dir' => $subDir ) +
$params ) );
558 unset( $subDirsRel ); // free directory for rmdir() on Windows (for FS backends)
562 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
563 if ( $dir === null ) {
564 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
566 return $status; // invalid storage path
569 // Attempt to lock this directory...
570 $filesLockEx = array( $params['dir'] );
571 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
572 if ( !$status->isOK() ) {
573 return $status; // abort
576 if ( $shard !== null ) { // confined to a single container/shard
577 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
578 $this->deleteContainerCache( $fullCont ); // purge cache
579 } else { // directory is on several shards
580 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
581 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
582 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
583 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
584 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
592 * @see FileBackendStore::doClean()
595 * @param array $params
598 protected function doCleanInternal( $container, $dir, array $params ) {
599 return Status
::newGood();
602 final public function fileExists( array $params ) {
603 $section = new ProfileSection( __METHOD__
. "-{$this->name}" );
604 $stat = $this->getFileStat( $params );
606 return ( $stat === null ) ?
null : (bool)$stat; // null => failure
609 final public function getFileTimestamp( array $params ) {
610 $section = new ProfileSection( __METHOD__
. "-{$this->name}" );
611 $stat = $this->getFileStat( $params );
613 return $stat ?
$stat['mtime'] : false;
616 final public function getFileSize( array $params ) {
617 $section = new ProfileSection( __METHOD__
. "-{$this->name}" );
618 $stat = $this->getFileStat( $params );
620 return $stat ?
$stat['size'] : false;
623 final public function getFileStat( array $params ) {
624 $path = self
::normalizeStoragePath( $params['src'] );
625 if ( $path === null ) {
626 return false; // invalid storage path
628 $section = new ProfileSection( __METHOD__
. "-{$this->name}" );
629 $latest = !empty( $params['latest'] ); // use latest data?
630 if ( !$this->cheapCache
->has( $path, 'stat', self
::CACHE_TTL
) ) {
631 $this->primeFileCache( array( $path ) ); // check persistent cache
633 if ( $this->cheapCache
->has( $path, 'stat', self
::CACHE_TTL
) ) {
634 $stat = $this->cheapCache
->get( $path, 'stat' );
635 // If we want the latest data, check that this cached
636 // value was in fact fetched with the latest available data.
637 if ( is_array( $stat ) ) {
638 if ( !$latest ||
$stat['latest'] ) {
641 } elseif ( in_array( $stat, array( 'NOT_EXIST', 'NOT_EXIST_LATEST' ) ) ) {
642 if ( !$latest ||
$stat === 'NOT_EXIST_LATEST' ) {
647 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
648 $stat = $this->doGetFileStat( $params );
649 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
650 if ( is_array( $stat ) ) { // file exists
651 $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 $section = new ProfileSection( __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 wfSuppressWarnings();
698 $contents[$path] = $fsFile ?
file_get_contents( $fsFile->getPath() ) : false;
705 final public function getFileXAttributes( array $params ) {
706 $path = self
::normalizeStoragePath( $params['src'] );
707 if ( $path === null ) {
708 return false; // invalid storage path
710 $section = new ProfileSection( __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 wfProfileIn( __METHOD__
. '-miss' );
721 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
722 $fields = $this->doGetFileXAttributes( $params );
723 $fields = is_array( $fields ) ? self
::normalizeXAttributes( $fields ) : false;
724 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
725 wfProfileOut( __METHOD__
. '-miss' );
726 $this->cheapCache
->set( $path, 'xattr', array( 'map' => $fields, 'latest' => $latest ) );
732 * @see FileBackendStore::getFileXAttributes()
733 * @return bool|string
735 protected function doGetFileXAttributes( array $params ) {
736 return array( 'headers' => array(), 'metadata' => array() ); // not supported
739 final public function getFileSha1Base36( array $params ) {
740 $path = self
::normalizeStoragePath( $params['src'] );
741 if ( $path === null ) {
742 return false; // invalid storage path
744 $section = new ProfileSection( __METHOD__
. "-{$this->name}" );
745 $latest = !empty( $params['latest'] ); // use latest data?
746 if ( $this->cheapCache
->has( $path, 'sha1', self
::CACHE_TTL
) ) {
747 $stat = $this->cheapCache
->get( $path, 'sha1' );
748 // If we want the latest data, check that this cached
749 // value was in fact fetched with the latest available data.
750 if ( !$latest ||
$stat['latest'] ) {
751 return $stat['hash'];
754 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
755 $hash = $this->doGetFileSha1Base36( $params );
756 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
757 $this->cheapCache
->set( $path, 'sha1', array( 'hash' => $hash, 'latest' => $latest ) );
763 * @see FileBackendStore::getFileSha1Base36()
764 * @param array $params
765 * @return bool|string
767 protected function doGetFileSha1Base36( array $params ) {
768 $fsFile = $this->getLocalReference( $params );
772 return $fsFile->getSha1Base36();
776 final public function getFileProps( array $params ) {
777 $section = new ProfileSection( __METHOD__
. "-{$this->name}" );
778 $fsFile = $this->getLocalReference( $params );
779 $props = $fsFile ?
$fsFile->getProps() : FSFile
::placeholderProps();
784 final public function getLocalReferenceMulti( array $params ) {
785 $section = new ProfileSection( __METHOD__
. "-{$this->name}" );
787 $params = $this->setConcurrencyFlags( $params );
789 $fsFiles = array(); // (path => FSFile)
790 $latest = !empty( $params['latest'] ); // use latest data?
791 // Reuse any files already in process cache...
792 foreach ( $params['srcs'] as $src ) {
793 $path = self
::normalizeStoragePath( $src );
794 if ( $path === null ) {
795 $fsFiles[$src] = null; // invalid storage path
796 } elseif ( $this->expensiveCache
->has( $path, 'localRef' ) ) {
797 $val = $this->expensiveCache
->get( $path, 'localRef' );
798 // If we want the latest data, check that this cached
799 // value was in fact fetched with the latest available data.
800 if ( !$latest ||
$val['latest'] ) {
801 $fsFiles[$src] = $val['object'];
805 // Fetch local references of any remaning files...
806 $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
807 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
808 $fsFiles[$path] = $fsFile;
809 if ( $fsFile ) { // update the process cache...
810 $this->expensiveCache
->set( $path, 'localRef',
811 array( 'object' => $fsFile, 'latest' => $latest ) );
819 * @see FileBackendStore::getLocalReferenceMulti()
820 * @param array $params
823 protected function doGetLocalReferenceMulti( array $params ) {
824 return $this->doGetLocalCopyMulti( $params );
827 final public function getLocalCopyMulti( array $params ) {
828 $section = new ProfileSection( __METHOD__
. "-{$this->name}" );
830 $params = $this->setConcurrencyFlags( $params );
831 $tmpFiles = $this->doGetLocalCopyMulti( $params );
837 * @see FileBackendStore::getLocalCopyMulti()
838 * @param array $params
841 abstract protected function doGetLocalCopyMulti( array $params );
844 * @see FileBackend::getFileHttpUrl()
845 * @param array $params
846 * @return string|null
848 public function getFileHttpUrl( array $params ) {
849 return null; // not supported
852 final public function streamFile( array $params ) {
853 $section = new ProfileSection( __METHOD__
. "-{$this->name}" );
854 $status = Status
::newGood();
856 $info = $this->getFileStat( $params );
857 if ( !$info ) { // let StreamFile handle the 404
858 $status->fatal( 'backend-fail-notexists', $params['src'] );
861 // Set output buffer and HTTP headers for stream
862 $extraHeaders = isset( $params['headers'] ) ?
$params['headers'] : array();
863 $res = StreamFile
::prepareForStream( $params['src'], $info, $extraHeaders );
864 if ( $res == StreamFile
::NOT_MODIFIED
) {
865 // do nothing; client cache is up to date
866 } elseif ( $res == StreamFile
::READY_STREAM
) {
867 wfProfileIn( __METHOD__
. '-send-' . $this->name
);
868 $status = $this->doStreamFile( $params );
869 wfProfileOut( __METHOD__
. '-send-' . $this->name
);
870 if ( !$status->isOK() ) {
871 // Per bug 41113, nasty things can happen if bad cache entries get
872 // stuck in cache. It's also possible that this error can come up
873 // with simple race conditions. Clear out the stat cache to be safe.
874 $this->clearCache( array( $params['src'] ) );
875 $this->deleteFileCache( $params['src'] );
876 trigger_error( "Bad stat cache or race condition for file {$params['src']}." );
879 $status->fatal( 'backend-fail-stream', $params['src'] );
886 * @see FileBackendStore::streamFile()
887 * @param array $params
890 protected function doStreamFile( array $params ) {
891 $status = Status
::newGood();
893 $fsFile = $this->getLocalReference( $params );
895 $status->fatal( 'backend-fail-stream', $params['src'] );
896 } elseif ( !readfile( $fsFile->getPath() ) ) {
897 $status->fatal( 'backend-fail-stream', $params['src'] );
903 final public function directoryExists( array $params ) {
904 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
905 if ( $dir === null ) {
906 return false; // invalid storage path
908 if ( $shard !== null ) { // confined to a single container/shard
909 return $this->doDirectoryExists( $fullCont, $dir, $params );
910 } else { // directory is on several shards
911 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
912 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
913 $res = false; // response
914 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
915 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
919 } elseif ( $exists === null ) { // error?
920 $res = null; // if we don't find anything, it is indeterminate
929 * @see FileBackendStore::directoryExists()
931 * @param string $container Resolved container name
932 * @param string $dir Resolved path relative to container
933 * @param array $params
936 abstract protected function doDirectoryExists( $container, $dir, array $params );
938 final public function getDirectoryList( array $params ) {
939 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
940 if ( $dir === null ) { // invalid storage path
943 if ( $shard !== null ) {
944 // File listing is confined to a single container/shard
945 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
947 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
948 // File listing spans multiple containers/shards
949 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
951 return new FileBackendStoreShardDirIterator( $this,
952 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
957 * Do not call this function from places outside FileBackend
959 * @see FileBackendStore::getDirectoryList()
961 * @param string $container Resolved container name
962 * @param string $dir Resolved path relative to container
963 * @param array $params
964 * @return Traversable|Array|null Returns null on failure
966 abstract public function getDirectoryListInternal( $container, $dir, array $params );
968 final public function getFileList( array $params ) {
969 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
970 if ( $dir === null ) { // invalid storage path
973 if ( $shard !== null ) {
974 // File listing is confined to a single container/shard
975 return $this->getFileListInternal( $fullCont, $dir, $params );
977 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
978 // File listing spans multiple containers/shards
979 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
981 return new FileBackendStoreShardFileIterator( $this,
982 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
987 * Do not call this function from places outside FileBackend
989 * @see FileBackendStore::getFileList()
991 * @param string $container Resolved container name
992 * @param string $dir Resolved path relative to container
993 * @param array $params
994 * @return Traversable|Array|null Returns null on failure
996 abstract public function getFileListInternal( $container, $dir, array $params );
999 * Return a list of FileOp objects from a list of operations.
1000 * Do not call this function from places outside FileBackend.
1002 * The result must have the same number of items as the input.
1003 * An exception is thrown if an unsupported operation is requested.
1005 * @param array $ops Same format as doOperations()
1006 * @return array List of FileOp objects
1007 * @throws FileBackendError
1009 final public function getOperationsInternal( array $ops ) {
1010 $supportedOps = array(
1011 'store' => 'StoreFileOp',
1012 'copy' => 'CopyFileOp',
1013 'move' => 'MoveFileOp',
1014 'delete' => 'DeleteFileOp',
1015 'create' => 'CreateFileOp',
1016 'describe' => 'DescribeFileOp',
1017 'null' => 'NullFileOp'
1020 $performOps = array(); // array of FileOp objects
1021 // Build up ordered array of FileOps...
1022 foreach ( $ops as $operation ) {
1023 $opName = $operation['op'];
1024 if ( isset( $supportedOps[$opName] ) ) {
1025 $class = $supportedOps[$opName];
1026 // Get params for this operation
1027 $params = $operation;
1028 // Append the FileOp class
1029 $performOps[] = new $class( $this, $params );
1031 throw new FileBackendError( "Operation '$opName' is not supported." );
1039 * Get a list of storage paths to lock for a list of operations
1040 * Returns an array with LockManager::LOCK_UW (shared locks) and
1041 * LockManager::LOCK_EX (exclusive locks) keys, each corresponding
1042 * to a list of storage paths to be locked. All returned paths are
1045 * @param array $performOps List of FileOp objects
1046 * @return array (LockManager::LOCK_UW => path list, LockManager::LOCK_EX => path list)
1048 final public function getPathsToLockForOpsInternal( array $performOps ) {
1049 // Build up a list of files to lock...
1050 $paths = array( 'sh' => array(), 'ex' => array() );
1051 foreach ( $performOps as $fileOp ) {
1052 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1053 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1055 // Optimization: if doing an EX lock anyway, don't also set an SH one
1056 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1057 // Get a shared lock on the parent directory of each path changed
1058 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1061 LockManager
::LOCK_UW
=> $paths['sh'],
1062 LockManager
::LOCK_EX
=> $paths['ex']
1066 public function getScopedLocksForOps( array $ops, Status
$status ) {
1067 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1069 return array( $this->getScopedFileLocks( $paths, 'mixed', $status ) );
1072 final protected function doOperationsInternal( array $ops, array $opts ) {
1073 $section = new ProfileSection( __METHOD__
. "-{$this->name}" );
1074 $status = Status
::newGood();
1076 // Fix up custom header name/value pairs...
1077 $ops = array_map( array( $this, 'stripInvalidHeadersFromOp' ), $ops );
1079 // Build up a list of FileOps...
1080 $performOps = $this->getOperationsInternal( $ops );
1082 // Acquire any locks as needed...
1083 if ( empty( $opts['nonLocking'] ) ) {
1084 // Build up a list of files to lock...
1085 $paths = $this->getPathsToLockForOpsInternal( $performOps );
1086 // Try to lock those files for the scope of this function...
1087 $scopeLock = $this->getScopedFileLocks( $paths, 'mixed', $status );
1088 if ( !$status->isOK() ) {
1089 return $status; // abort
1093 // Clear any file cache entries (after locks acquired)
1094 if ( empty( $opts['preserveCache'] ) ) {
1095 $this->clearCache();
1098 // Build the list of paths involved
1100 foreach ( $performOps as $op ) {
1101 $paths = array_merge( $paths, $op->storagePathsRead() );
1102 $paths = array_merge( $paths, $op->storagePathsChanged() );
1104 // Load from the persistent container caches
1105 $this->primeContainerCache( $paths );
1106 // Get the latest stat info for all the files (having locked them)
1107 $this->preloadFileStat( array( 'srcs' => $paths, 'latest' => true ) );
1109 // Actually attempt the operation batch...
1110 $opts = $this->setConcurrencyFlags( $opts );
1111 $subStatus = FileOpBatch
::attempt( $performOps, $opts, $this->fileJournal
);
1113 // Merge errors into status fields
1114 $status->merge( $subStatus );
1115 $status->success
= $subStatus->success
; // not done in merge()
1120 final protected function doQuickOperationsInternal( array $ops ) {
1121 $section = new ProfileSection( __METHOD__
. "-{$this->name}" );
1122 $status = Status
::newGood();
1124 // Fix up custom header name/value pairs...
1125 $ops = array_map( array( $this, 'stripInvalidHeadersFromOp' ), $ops );
1127 // Clear any file cache entries
1128 $this->clearCache();
1130 $supportedOps = array( 'create', 'store', 'copy', 'move', 'delete', 'describe', 'null' );
1131 $async = ( $this->parallelize
=== 'implicit' && count( $ops ) > 1 );
1132 $maxConcurrency = $this->concurrency
; // throttle
1134 $statuses = array(); // array of (index => Status)
1135 $fileOpHandles = array(); // list of (index => handle) arrays
1136 $curFileOpHandles = array(); // current handle batch
1137 // Perform the sync-only ops and build up op handles for the async ops...
1138 foreach ( $ops as $index => $params ) {
1139 if ( !in_array( $params['op'], $supportedOps ) ) {
1140 throw new FileBackendError( "Operation '{$params['op']}' is not supported." );
1142 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1143 $subStatus = $this->$method( array( 'async' => $async ) +
$params );
1144 if ( $subStatus->value
instanceof FileBackendStoreOpHandle
) { // async
1145 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1146 $fileOpHandles[] = $curFileOpHandles; // push this batch
1147 $curFileOpHandles = array();
1149 $curFileOpHandles[$index] = $subStatus->value
; // keep index
1150 } else { // error or completed
1151 $statuses[$index] = $subStatus; // keep index
1154 if ( count( $curFileOpHandles ) ) {
1155 $fileOpHandles[] = $curFileOpHandles; // last batch
1157 // Do all the async ops that can be done concurrently...
1158 foreach ( $fileOpHandles as $fileHandleBatch ) {
1159 $statuses = $statuses +
$this->executeOpHandlesInternal( $fileHandleBatch );
1161 // Marshall and merge all the responses...
1162 foreach ( $statuses as $index => $subStatus ) {
1163 $status->merge( $subStatus );
1164 if ( $subStatus->isOK() ) {
1165 $status->success
[$index] = true;
1166 ++
$status->successCount
;
1168 $status->success
[$index] = false;
1169 ++
$status->failCount
;
1177 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1178 * The resulting Status object fields will correspond
1179 * to the order in which the handles where given.
1181 * @param array $fileOpHandles
1182 * @throws FileBackendError
1183 * @internal param array $handles List of FileBackendStoreOpHandle objects
1184 * @return array Map of Status objects
1186 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1187 $section = new ProfileSection( __METHOD__
. "-{$this->name}" );
1189 foreach ( $fileOpHandles as $fileOpHandle ) {
1190 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle
) ) {
1191 throw new FileBackendError( "Given a non-FileBackendStoreOpHandle object." );
1192 } elseif ( $fileOpHandle->backend
->getName() !== $this->getName() ) {
1193 throw new FileBackendError( "Given a FileBackendStoreOpHandle for the wrong backend." );
1196 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1197 foreach ( $fileOpHandles as $fileOpHandle ) {
1198 $fileOpHandle->closeResources();
1205 * @see FileBackendStore::executeOpHandlesInternal()
1206 * @param array $fileOpHandles
1207 * @throws FileBackendError
1208 * @return array List of corresponding Status objects
1210 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1211 if ( count( $fileOpHandles ) ) {
1212 throw new FileBackendError( "This backend supports no asynchronous operations." );
1219 * Strip long HTTP headers from a file operation.
1220 * Most headers are just numbers, but some are allowed to be long.
1221 * This function is useful for cleaning up headers and avoiding backend
1222 * specific errors, especially in the middle of batch file operations.
1224 * @param array $op Same format as doOperation()
1227 protected function stripInvalidHeadersFromOp( array $op ) {
1228 static $longs = array( 'Content-Disposition' );
1229 if ( isset( $op['headers'] ) ) { // op sets HTTP headers
1230 foreach ( $op['headers'] as $name => $value ) {
1231 $maxHVLen = in_array( $name, $longs ) ? INF
: 255;
1232 if ( strlen( $name ) > 255 ||
strlen( $value ) > $maxHVLen ) {
1233 trigger_error( "Header '$name: $value' is too long." );
1234 unset( $op['headers'][$name] );
1235 } elseif ( !strlen( $value ) ) {
1236 $op['headers'][$name] = ''; // null/false => ""
1244 final public function preloadCache( array $paths ) {
1245 $fullConts = array(); // full container names
1246 foreach ( $paths as $path ) {
1247 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1248 $fullConts[] = $fullCont;
1250 // Load from the persistent file and container caches
1251 $this->primeContainerCache( $fullConts );
1252 $this->primeFileCache( $paths );
1255 final public function clearCache( array $paths = null ) {
1256 if ( is_array( $paths ) ) {
1257 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1258 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1260 if ( $paths === null ) {
1261 $this->cheapCache
->clear();
1262 $this->expensiveCache
->clear();
1264 foreach ( $paths as $path ) {
1265 $this->cheapCache
->clear( $path );
1266 $this->expensiveCache
->clear( $path );
1269 $this->doClearCache( $paths );
1273 * Clears any additional stat caches for storage paths
1275 * @see FileBackend::clearCache()
1277 * @param array $paths Storage paths (optional)
1279 protected function doClearCache( array $paths = null ) {
1282 final public function preloadFileStat( array $params ) {
1283 $section = new ProfileSection( __METHOD__
. "-{$this->name}" );
1285 $params['concurrency'] = ( $this->parallelize
!== 'off' ) ?
$this->concurrency
: 1;
1286 $stats = $this->doGetFileStatMulti( $params );
1287 if ( $stats === null ) {
1288 return; // not supported
1291 $latest = !empty( $params['latest'] ); // use latest data?
1292 foreach ( $stats as $path => $stat ) {
1293 $path = FileBackend
::normalizeStoragePath( $path );
1294 if ( $path === null ) {
1295 continue; // this shouldn't happen
1297 if ( is_array( $stat ) ) { // file exists
1298 $stat['latest'] = $latest;
1299 $this->cheapCache
->set( $path, 'stat', $stat );
1300 $this->setFileCache( $path, $stat ); // update persistent cache
1301 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
1302 $this->cheapCache
->set( $path, 'sha1',
1303 array( 'hash' => $stat['sha1'], 'latest' => $latest ) );
1305 if ( isset( $stat['xattr'] ) ) { // some backends store headers/metadata
1306 $stat['xattr'] = self
::normalizeXAttributes( $stat['xattr'] );
1307 $this->cheapCache
->set( $path, 'xattr',
1308 array( 'map' => $stat['xattr'], 'latest' => $latest ) );
1310 } elseif ( $stat === false ) { // file does not exist
1311 $this->cheapCache
->set( $path, 'stat',
1312 $latest ?
'NOT_EXIST_LATEST' : 'NOT_EXIST' );
1313 $this->cheapCache
->set( $path, 'xattr',
1314 array( 'map' => false, 'latest' => $latest ) );
1315 $this->cheapCache
->set( $path, 'sha1',
1316 array( 'hash' => false, 'latest' => $latest ) );
1317 wfDebug( __METHOD__
. ": File $path does not exist.\n" );
1318 } else { // an error occurred
1319 wfDebug( __METHOD__
. ": Could not stat file $path.\n" );
1325 * Get file stat information (concurrently if possible) for several files
1327 * @see FileBackend::getFileStat()
1329 * @param array $params Parameters include:
1330 * - srcs : list of source storage paths
1331 * - latest : use the latest available data
1332 * @return array|null Map of storage paths to array|bool|null (returns null if not supported)
1335 protected function doGetFileStatMulti( array $params ) {
1336 return null; // not supported
1340 * Is this a key/value store where directories are just virtual?
1341 * Virtual directories exists in so much as files exists that are
1342 * prefixed with the directory path followed by a forward slash.
1346 abstract protected function directoriesAreVirtual();
1349 * Check if a container name is valid.
1350 * This checks for for length and illegal characters.
1352 * @param string $container
1355 final protected static function isValidContainerName( $container ) {
1356 // This accounts for Swift and S3 restrictions while leaving room
1357 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1358 // This disallows directory separators or traversal characters.
1359 // Note that matching strings URL encode to the same string;
1360 // in Swift, the length restriction is *after* URL encoding.
1361 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1365 * Splits a storage path into an internal container name,
1366 * an internal relative file name, and a container shard suffix.
1367 * Any shard suffix is already appended to the internal container name.
1368 * This also checks that the storage path is valid and within this backend.
1370 * If the container is sharded but a suffix could not be determined,
1371 * this means that the path can only refer to a directory and can only
1372 * be scanned by looking in all the container shards.
1374 * @param string $storagePath
1375 * @return array (container, path, container suffix) or (null, null, null) if invalid
1377 final protected function resolveStoragePath( $storagePath ) {
1378 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1379 if ( $backend === $this->name
) { // must be for this backend
1380 $relPath = self
::normalizeContainerPath( $relPath );
1381 if ( $relPath !== null ) {
1382 // Get shard for the normalized path if this container is sharded
1383 $cShard = $this->getContainerShard( $container, $relPath );
1384 // Validate and sanitize the relative path (backend-specific)
1385 $relPath = $this->resolveContainerPath( $container, $relPath );
1386 if ( $relPath !== null ) {
1387 // Prepend any wiki ID prefix to the container name
1388 $container = $this->fullContainerName( $container );
1389 if ( self
::isValidContainerName( $container ) ) {
1390 // Validate and sanitize the container name (backend-specific)
1391 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1392 if ( $container !== null ) {
1393 return array( $container, $relPath, $cShard );
1400 return array( null, null, null );
1404 * Like resolveStoragePath() except null values are returned if
1405 * the container is sharded and the shard could not be determined
1406 * or if the path ends with '/'. The later case is illegal for FS
1407 * backends and can confuse listings for object store backends.
1409 * This function is used when resolving paths that must be valid
1410 * locations for files. Directory and listing functions should
1411 * generally just use resolveStoragePath() instead.
1413 * @see FileBackendStore::resolveStoragePath()
1415 * @param string $storagePath
1416 * @return array (container, path) or (null, null) if invalid
1418 final protected function resolveStoragePathReal( $storagePath ) {
1419 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1420 if ( $cShard !== null && substr( $relPath, -1 ) !== '/' ) {
1421 return array( $container, $relPath );
1424 return array( null, null );
1428 * Get the container name shard suffix for a given path.
1429 * Any empty suffix means the container is not sharded.
1431 * @param string $container Container name
1432 * @param string $relPath Storage path relative to the container
1433 * @return string|null Returns null if shard could not be determined
1435 final protected function getContainerShard( $container, $relPath ) {
1436 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1437 if ( $levels == 1 ||
$levels == 2 ) {
1438 // Hash characters are either base 16 or 36
1439 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1440 // Get a regex that represents the shard portion of paths.
1441 // The concatenation of the captures gives us the shard.
1442 if ( $levels === 1 ) { // 16 or 36 shards per container
1443 $hashDirRegex = '(' . $char . ')';
1444 } else { // 256 or 1296 shards per container
1445 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1446 $hashDirRegex = $char . '/(' . $char . '{2})';
1447 } else { // short hash dir format (e.g. "a/b/c")
1448 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1451 // Allow certain directories to be above the hash dirs so as
1452 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1453 // They must be 2+ chars to avoid any hash directory ambiguity.
1455 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1456 return '.' . implode( '', array_slice( $m, 1 ) );
1459 return null; // failed to match
1462 return ''; // no sharding
1466 * Check if a storage path maps to a single shard.
1467 * Container dirs like "a", where the container shards on "x/xy",
1468 * can reside on several shards. Such paths are tricky to handle.
1470 * @param string $storagePath Storage path
1473 final public function isSingleShardPathInternal( $storagePath ) {
1474 list( , , $shard ) = $this->resolveStoragePath( $storagePath );
1476 return ( $shard !== null );
1480 * Get the sharding config for a container.
1481 * If greater than 0, then all file storage paths within
1482 * the container are required to be hashed accordingly.
1484 * @param string $container
1485 * @return array (integer levels, integer base, repeat flag) or (0, 0, false)
1487 final protected function getContainerHashLevels( $container ) {
1488 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1489 $config = $this->shardViaHashLevels
[$container];
1490 $hashLevels = (int)$config['levels'];
1491 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1492 $hashBase = (int)$config['base'];
1493 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1494 return array( $hashLevels, $hashBase, $config['repeat'] );
1499 return array( 0, 0, false ); // no sharding
1503 * Get a list of full container shard suffixes for a container
1505 * @param string $container
1508 final protected function getContainerSuffixes( $container ) {
1510 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1511 if ( $digits > 0 ) {
1512 $numShards = pow( $base, $digits );
1513 for ( $index = 0; $index < $numShards; $index++
) {
1514 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1522 * Get the full container name, including the wiki ID prefix
1524 * @param string $container
1527 final protected function fullContainerName( $container ) {
1528 if ( $this->wikiId
!= '' ) {
1529 return "{$this->wikiId}-$container";
1536 * Resolve a container name, checking if it's allowed by the backend.
1537 * This is intended for internal use, such as encoding illegal chars.
1538 * Subclasses can override this to be more restrictive.
1540 * @param string $container
1541 * @return string|null
1543 protected function resolveContainerName( $container ) {
1548 * Resolve a relative storage path, checking if it's allowed by the backend.
1549 * This is intended for internal use, such as encoding illegal chars or perhaps
1550 * getting absolute paths (e.g. FS based backends). Note that the relative path
1551 * may be the empty string (e.g. the path is simply to the container).
1553 * @param string $container Container name
1554 * @param string $relStoragePath Storage path relative to the container
1555 * @return string|null Path or null if not valid
1557 protected function resolveContainerPath( $container, $relStoragePath ) {
1558 return $relStoragePath;
1562 * Get the cache key for a container
1564 * @param string $container Resolved container name
1567 private function containerCacheKey( $container ) {
1568 return "filebackend:{$this->name}:{$this->wikiId}:container:{$container}";
1572 * Set the cached info for a container
1574 * @param string $container Resolved container name
1575 * @param array $val Information to cache
1577 final protected function setContainerCache( $container, array $val ) {
1578 $this->memCache
->add( $this->containerCacheKey( $container ), $val, 14 * 86400 );
1582 * Delete the cached info for a container.
1583 * The cache key is salted for a while to prevent race conditions.
1585 * @param string $container Resolved container name
1587 final protected function deleteContainerCache( $container ) {
1588 if ( !$this->memCache
->set( $this->containerCacheKey( $container ), 'PURGED', 300 ) ) {
1589 trigger_error( "Unable to delete stat cache for container $container." );
1594 * Do a batch lookup from cache for container stats for all containers
1595 * used in a list of container names or storage paths objects.
1596 * This loads the persistent cache values into the process cache.
1598 * @param array $items
1600 final protected function primeContainerCache( array $items ) {
1601 $section = new ProfileSection( __METHOD__
. "-{$this->name}" );
1603 $paths = array(); // list of storage paths
1604 $contNames = array(); // (cache key => resolved container name)
1605 // Get all the paths/containers from the items...
1606 foreach ( $items as $item ) {
1607 if ( self
::isStoragePath( $item ) ) {
1609 } elseif ( is_string( $item ) ) { // full container name
1610 $contNames[$this->containerCacheKey( $item )] = $item;
1613 // Get all the corresponding cache keys for paths...
1614 foreach ( $paths as $path ) {
1615 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1616 if ( $fullCont !== null ) { // valid path for this backend
1617 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1621 $contInfo = array(); // (resolved container name => cache value)
1622 // Get all cache entries for these container cache keys...
1623 $values = $this->memCache
->getMulti( array_keys( $contNames ) );
1624 foreach ( $values as $cacheKey => $val ) {
1625 $contInfo[$contNames[$cacheKey]] = $val;
1628 // Populate the container process cache for the backend...
1629 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1633 * Fill the backend-specific process cache given an array of
1634 * resolved container names and their corresponding cached info.
1635 * Only containers that actually exist should appear in the map.
1637 * @param array $containerInfo Map of resolved container names to cached info
1639 protected function doPrimeContainerCache( array $containerInfo ) {
1643 * Get the cache key for a file path
1645 * @param string $path Normalized storage path
1648 private function fileCacheKey( $path ) {
1649 return "filebackend:{$this->name}:{$this->wikiId}:file:" . sha1( $path );
1653 * Set the cached stat info for a file path.
1654 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1655 * salting for the case when a file is created at a path were there was none before.
1657 * @param string $path Storage path
1658 * @param array $val Stat information to cache
1660 final protected function setFileCache( $path, array $val ) {
1661 $path = FileBackend
::normalizeStoragePath( $path );
1662 if ( $path === null ) {
1663 return; // invalid storage path
1665 $age = time() - wfTimestamp( TS_UNIX
, $val['mtime'] );
1666 $ttl = min( 7 * 86400, max( 300, floor( .1 * $age ) ) );
1667 $this->memCache
->add( $this->fileCacheKey( $path ), $val, $ttl );
1671 * Delete the cached stat info for a file path.
1672 * The cache key is salted for a while to prevent race conditions.
1673 * Since negatives (404s) are not cached, this does not need to be called when
1674 * a file is created at a path were there was none before.
1676 * @param string $path Storage path
1678 final protected function deleteFileCache( $path ) {
1679 $path = FileBackend
::normalizeStoragePath( $path );
1680 if ( $path === null ) {
1681 return; // invalid storage path
1683 if ( !$this->memCache
->set( $this->fileCacheKey( $path ), 'PURGED', 300 ) ) {
1684 trigger_error( "Unable to delete stat cache for file $path." );
1689 * Do a batch lookup from cache for file stats for all paths
1690 * used in a list of storage paths or FileOp objects.
1691 * This loads the persistent cache values into the process cache.
1693 * @param array $items List of storage paths
1695 final protected function primeFileCache( array $items ) {
1696 $section = new ProfileSection( __METHOD__
. "-{$this->name}" );
1698 $paths = array(); // list of storage paths
1699 $pathNames = array(); // (cache key => storage path)
1700 // Get all the paths/containers from the items...
1701 foreach ( $items as $item ) {
1702 if ( self
::isStoragePath( $item ) ) {
1703 $paths[] = FileBackend
::normalizeStoragePath( $item );
1706 // Get rid of any paths that failed normalization...
1707 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1708 // Get all the corresponding cache keys for paths...
1709 foreach ( $paths as $path ) {
1710 list( , $rel, ) = $this->resolveStoragePath( $path );
1711 if ( $rel !== null ) { // valid path for this backend
1712 $pathNames[$this->fileCacheKey( $path )] = $path;
1715 // Get all cache entries for these container cache keys...
1716 $values = $this->memCache
->getMulti( array_keys( $pathNames ) );
1717 foreach ( $values as $cacheKey => $val ) {
1718 if ( is_array( $val ) ) {
1719 $path = $pathNames[$cacheKey];
1720 $this->cheapCache
->set( $path, 'stat', $val );
1721 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1722 $this->cheapCache
->set( $path, 'sha1',
1723 array( 'hash' => $val['sha1'], 'latest' => $val['latest'] ) );
1725 if ( isset( $val['xattr'] ) ) { // some backends store headers/metadata
1726 $val['xattr'] = self
::normalizeXAttributes( $val['xattr'] );
1727 $this->cheapCache
->set( $path, 'xattr',
1728 array( 'map' => $val['xattr'], 'latest' => $val['latest'] ) );
1735 * Normalize file headers/metadata to the FileBackend::getFileXAttributes() format
1737 * @param array $xattr
1741 final protected static function normalizeXAttributes( array $xattr ) {
1742 $newXAttr = array( 'headers' => array(), 'metadata' => array() );
1744 foreach ( $xattr['headers'] as $name => $value ) {
1745 $newXAttr['headers'][strtolower( $name )] = $value;
1748 foreach ( $xattr['metadata'] as $name => $value ) {
1749 $newXAttr['metadata'][strtolower( $name )] = $value;
1756 * Set the 'concurrency' option from a list of operation options
1758 * @param array $opts Map of operation options
1761 final protected function setConcurrencyFlags( array $opts ) {
1762 $opts['concurrency'] = 1; // off
1763 if ( $this->parallelize
=== 'implicit' ) {
1764 if ( !isset( $opts['parallelize'] ) ||
$opts['parallelize'] ) {
1765 $opts['concurrency'] = $this->concurrency
;
1767 } elseif ( $this->parallelize
=== 'explicit' ) {
1768 if ( !empty( $opts['parallelize'] ) ) {
1769 $opts['concurrency'] = $this->concurrency
;
1777 * Get the content type to use in HEAD/GET requests for a file
1779 * @param string $storagePath
1780 * @param string|null $content File data
1781 * @param string|null $fsPath File system path
1784 protected function getContentType( $storagePath, $content, $fsPath ) {
1785 return call_user_func_array( $this->mimeCallback
, func_get_args() );
1790 * FileBackendStore helper class for performing asynchronous file operations.
1792 * For example, calling FileBackendStore::createInternal() with the "async"
1793 * param flag may result in a Status that contains this object as a value.
1794 * This class is largely backend-specific and is mostly just "magic" to be
1795 * passed to FileBackendStore::executeOpHandlesInternal().
1797 abstract class FileBackendStoreOpHandle
{
1799 public $params = array(); // params to caller functions
1800 /** @var FileBackendStore */
1803 public $resourcesToClose = array();
1805 public $call; // string; name that identifies the function called
1808 * Close all open file handles
1810 public function closeResources() {
1811 array_map( 'fclose', $this->resourcesToClose
);
1816 * FileBackendStore helper function to handle listings that span container shards.
1817 * Do not use this class from places outside of FileBackendStore.
1819 * @ingroup FileBackend
1821 abstract class FileBackendStoreShardListIterator
extends FilterIterator
{
1822 /** @var FileBackendStore */
1828 /** @var string Full container name */
1829 protected $container;
1831 /** @var string Resolved relative path */
1832 protected $directory;
1835 protected $multiShardPaths = array(); // (rel path => 1)
1838 * @param FileBackendStore $backend
1839 * @param string $container Full storage container name
1840 * @param string $dir Storage directory relative to container
1841 * @param array $suffixes List of container shard suffixes
1842 * @param array $params
1844 public function __construct(
1845 FileBackendStore
$backend, $container, $dir, array $suffixes, array $params
1847 $this->backend
= $backend;
1848 $this->container
= $container;
1849 $this->directory
= $dir;
1850 $this->params
= $params;
1852 $iter = new AppendIterator();
1853 foreach ( $suffixes as $suffix ) {
1854 $iter->append( $this->listFromShard( $this->container
. $suffix ) );
1857 parent
::__construct( $iter );
1860 public function accept() {
1861 $rel = $this->getInnerIterator()->current(); // path relative to given directory
1862 $path = $this->params
['dir'] . "/{$rel}"; // full storage path
1863 if ( $this->backend
->isSingleShardPathInternal( $path ) ) {
1864 return true; // path is only on one shard; no issue with duplicates
1865 } elseif ( isset( $this->multiShardPaths
[$rel] ) ) {
1866 // Don't keep listing paths that are on multiple shards
1869 $this->multiShardPaths
[$rel] = 1;
1875 public function rewind() {
1877 $this->multiShardPaths
= array();
1881 * Get the list for a given container shard
1883 * @param string $container Resolved container name
1886 abstract protected function listFromShard( $container );
1890 * Iterator for listing directories
1892 class FileBackendStoreShardDirIterator
extends FileBackendStoreShardListIterator
{
1893 protected function listFromShard( $container ) {
1894 $list = $this->backend
->getDirectoryListInternal(
1895 $container, $this->directory
, $this->params
);
1896 if ( $list === null ) {
1897 return new ArrayIterator( array() );
1899 return is_array( $list ) ?
new ArrayIterator( $list ) : $list;
1905 * Iterator for listing regular files
1907 class FileBackendStoreShardFileIterator
extends FileBackendStoreShardListIterator
{
1908 protected function listFromShard( $container ) {
1909 $list = $this->backend
->getFileListInternal(
1910 $container, $this->directory
, $this->params
);
1911 if ( $list === null ) {
1912 return new ArrayIterator( array() );
1914 return is_array( $list ) ?
new ArrayIterator( $list ) : $list;