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 */
42 protected $cheapCache; // Map of paths to small (RAM/disk) cache items
43 /** @var ProcessCacheLRU */
44 protected $expensiveCache; // Map of paths to large (RAM/disk) cache items
46 /** @var Array Map of container names to sharding settings */
47 protected $shardViaHashLevels = array(); // (container name => config array)
49 protected $maxFileSize = 4294967296; // integer bytes (4GiB)
51 const CACHE_TTL
= 10; // integer; TTL in seconds for process cache entries
54 * @see FileBackend::__construct()
56 * @param $config Array
58 public function __construct( array $config ) {
59 parent
::__construct( $config );
60 $this->memCache
= new EmptyBagOStuff(); // disabled by default
61 $this->cheapCache
= new ProcessCacheLRU( 300 );
62 $this->expensiveCache
= new ProcessCacheLRU( 5 );
66 * Get the maximum allowable file size given backend
67 * medium restrictions and basic performance constraints.
68 * Do not call this function from places outside FileBackend and FileOp.
70 * @return integer Bytes
72 final public function maxFileSizeInternal() {
73 return $this->maxFileSize
;
77 * Check if a file can be created or changed at a given storage path.
78 * FS backends should check if the parent directory exists, files can be
79 * written under it, and that any file already there is writable.
80 * Backends using key/value stores should check if the container exists.
82 * @param $storagePath string
85 abstract public function isPathUsableInternal( $storagePath );
88 * Create a file in the backend with the given contents.
89 * This will overwrite any file that exists at the destination.
90 * Do not call this function from places outside FileBackend and FileOp.
93 * - content : the raw file contents
94 * - dst : destination storage path
95 * - disposition : Content-Disposition header value for the destination
96 * - async : Status will be returned immediately if supported.
97 * If the status is OK, then its value field will be
98 * set to a FileBackendStoreOpHandle object.
100 * @param $params Array
103 final public function createInternal( array $params ) {
104 wfProfileIn( __METHOD__
);
105 wfProfileIn( __METHOD__
. '-' . $this->name
);
106 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
107 $status = Status
::newFatal( 'backend-fail-maxsize',
108 $params['dst'], $this->maxFileSizeInternal() );
110 $status = $this->doCreateInternal( $params );
111 $this->clearCache( array( $params['dst'] ) );
112 $this->deleteFileCache( $params['dst'] ); // persistent cache
114 wfProfileOut( __METHOD__
. '-' . $this->name
);
115 wfProfileOut( __METHOD__
);
120 * @see FileBackendStore::createInternal()
122 abstract protected function doCreateInternal( array $params );
125 * Store a file into the backend from a file on disk.
126 * This will overwrite any file that exists at the destination.
127 * Do not call this function from places outside FileBackend and FileOp.
130 * - src : source path on disk
131 * - dst : destination storage path
132 * - disposition : Content-Disposition header value for the destination
133 * - async : Status will be returned immediately if supported.
134 * If the status is OK, then its value field will be
135 * set to a FileBackendStoreOpHandle object.
137 * @param $params Array
140 final public function storeInternal( array $params ) {
141 wfProfileIn( __METHOD__
);
142 wfProfileIn( __METHOD__
. '-' . $this->name
);
143 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
144 $status = Status
::newFatal( 'backend-fail-maxsize',
145 $params['dst'], $this->maxFileSizeInternal() );
147 $status = $this->doStoreInternal( $params );
148 $this->clearCache( array( $params['dst'] ) );
149 $this->deleteFileCache( $params['dst'] ); // persistent cache
151 wfProfileOut( __METHOD__
. '-' . $this->name
);
152 wfProfileOut( __METHOD__
);
157 * @see FileBackendStore::storeInternal()
159 abstract protected function doStoreInternal( array $params );
162 * Copy a file from one storage path to another in the backend.
163 * This will overwrite any file that exists at the destination.
164 * Do not call this function from places outside FileBackend and FileOp.
167 * - src : source storage path
168 * - dst : destination storage path
169 * - ignoreMissingSource : do nothing if the source file does not exist
170 * - disposition : Content-Disposition header value for the destination
171 * - async : Status will be returned immediately if supported.
172 * If the status is OK, then its value field will be
173 * set to a FileBackendStoreOpHandle object.
175 * @param $params Array
178 final public function copyInternal( array $params ) {
179 wfProfileIn( __METHOD__
);
180 wfProfileIn( __METHOD__
. '-' . $this->name
);
181 $status = $this->doCopyInternal( $params );
182 $this->clearCache( array( $params['dst'] ) );
183 $this->deleteFileCache( $params['dst'] ); // persistent cache
184 wfProfileOut( __METHOD__
. '-' . $this->name
);
185 wfProfileOut( __METHOD__
);
190 * @see FileBackendStore::copyInternal()
192 abstract protected function doCopyInternal( array $params );
195 * Delete a file at the storage path.
196 * Do not call this function from places outside FileBackend and FileOp.
199 * - src : source storage path
200 * - ignoreMissingSource : do nothing if the source file does not exist
201 * - async : Status will be returned immediately if supported.
202 * If the status is OK, then its value field will be
203 * set to a FileBackendStoreOpHandle object.
205 * @param $params Array
208 final public function deleteInternal( array $params ) {
209 wfProfileIn( __METHOD__
);
210 wfProfileIn( __METHOD__
. '-' . $this->name
);
211 $status = $this->doDeleteInternal( $params );
212 $this->clearCache( array( $params['src'] ) );
213 $this->deleteFileCache( $params['src'] ); // persistent cache
214 wfProfileOut( __METHOD__
. '-' . $this->name
);
215 wfProfileOut( __METHOD__
);
220 * @see FileBackendStore::deleteInternal()
222 abstract protected function doDeleteInternal( array $params );
225 * Move a file from one storage path to another in the backend.
226 * This will overwrite any file that exists at the destination.
227 * Do not call this function from places outside FileBackend and FileOp.
230 * - src : source storage path
231 * - dst : destination storage path
232 * - ignoreMissingSource : do nothing if the source file does not exist
233 * - disposition : Content-Disposition header value for the destination
234 * - async : Status will be returned immediately if supported.
235 * If the status is OK, then its value field will be
236 * set to a FileBackendStoreOpHandle object.
238 * @param $params Array
241 final public function moveInternal( array $params ) {
242 wfProfileIn( __METHOD__
);
243 wfProfileIn( __METHOD__
. '-' . $this->name
);
244 $status = $this->doMoveInternal( $params );
245 $this->clearCache( array( $params['src'], $params['dst'] ) );
246 $this->deleteFileCache( $params['src'] ); // persistent cache
247 $this->deleteFileCache( $params['dst'] ); // persistent cache
248 wfProfileOut( __METHOD__
. '-' . $this->name
);
249 wfProfileOut( __METHOD__
);
254 * @see FileBackendStore::moveInternal()
257 protected function doMoveInternal( array $params ) {
258 unset( $params['async'] ); // two steps, won't work here :)
259 // Copy source to dest
260 $status = $this->copyInternal( $params );
261 if ( $status->isOK() ) {
262 // Delete source (only fails due to races or medium going down)
263 $status->merge( $this->deleteInternal( array( 'src' => $params['src'] ) ) );
264 $status->setResult( true, $status->value
); // ignore delete() errors
270 * No-op file operation that does nothing.
271 * Do not call this function from places outside FileBackend and FileOp.
273 * @param $params Array
276 final public function nullInternal( array $params ) {
277 return Status
::newGood();
281 * @see FileBackend::concatenate()
284 final public function concatenate( array $params ) {
285 wfProfileIn( __METHOD__
);
286 wfProfileIn( __METHOD__
. '-' . $this->name
);
287 $status = Status
::newGood();
289 // Try to lock the source files for the scope of this function
290 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager
::LOCK_UW
, $status );
291 if ( $status->isOK() ) {
292 // Actually do the file concatenation...
293 $start_time = microtime( true );
294 $status->merge( $this->doConcatenate( $params ) );
295 $sec = microtime( true ) - $start_time;
296 if ( !$status->isOK() ) {
297 wfDebugLog( 'FileOperation', get_class( $this ) . " failed to concatenate " .
298 count( $params['srcs'] ) . " file(s) [$sec sec]" );
302 wfProfileOut( __METHOD__
. '-' . $this->name
);
303 wfProfileOut( __METHOD__
);
308 * @see FileBackendStore::concatenate()
311 protected function doConcatenate( array $params ) {
312 $status = Status
::newGood();
314 $tmpPath = $params['dst']; // convenience
315 unset( $params['latest'] ); // sanity
316 $callback = isset( $params['callback'] )
317 ?
$params['callback']
318 : function( Status
$status, $segment ) {};
320 // Check that the specified temp file is valid...
321 wfSuppressWarnings();
322 $ok = ( is_file( $tmpPath ) && filesize( $tmpPath ) == 0 );
324 if ( !$ok ) { // not present or not empty
325 $status->fatal( 'backend-fail-opentemp', $tmpPath );
326 $callback( $status, null ); // update progress
330 // Get local FS versions of the chunks needed for the concatenation...
331 $fsFiles = $this->getLocalReferenceMulti( $params );
332 foreach ( $fsFiles as $path => &$fsFile ) {
333 if ( !$fsFile ) { // chunk failed to download?
334 $fsFile = $this->getLocalReference( array( 'src' => $path ) );
335 if ( !$fsFile ) { // retry failed?
336 $status->fatal( 'backend-fail-read', $path );
337 $callback( $status, null ); // update progress
342 unset( $fsFile ); // unset reference so we can reuse $fsFile
344 // Get a handle for the destination temp file
345 $tmpHandle = fopen( $tmpPath, 'ab' );
346 if ( $tmpHandle === false ) {
347 $status->fatal( 'backend-fail-opentemp', $tmpPath );
348 $callback( $status, null ); // update progress
352 $segment = 0; // segment number
353 // Build up the temp file using the source chunks (in order)...
354 foreach ( $fsFiles as $virtualSource => $fsFile ) {
355 ++
$segment; // first segment is "1"
356 // Get a handle to the local FS version
357 $sourceHandle = fopen( $fsFile->getPath(), 'rb' );
358 if ( $sourceHandle === false ) {
359 fclose( $tmpHandle );
360 $status->fatal( 'backend-fail-read', $virtualSource );
361 $callback( $status, null ); // update progress
364 // Append chunk to file (pass chunk size to avoid magic quotes)
365 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
366 fclose( $sourceHandle );
367 fclose( $tmpHandle );
368 $status->fatal( 'backend-fail-writetemp', $tmpPath );
369 $callback( $status , null );
372 fclose( $sourceHandle );
373 $callback( $status, $segment ); // update progress (chunk success)
375 if ( !fclose( $tmpHandle ) ) {
376 $status->fatal( 'backend-fail-closetemp', $tmpPath );
377 $callback( $status, null ); // update progress
381 clearstatcache(); // temp file changed
382 $callback( $status, null ); // update progress (full success)
388 * @see FileBackend::doPrepare()
391 final protected function doPrepare( array $params ) {
392 wfProfileIn( __METHOD__
);
393 wfProfileIn( __METHOD__
. '-' . $this->name
);
395 $status = Status
::newGood();
396 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
397 if ( $dir === null ) {
398 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
399 wfProfileOut( __METHOD__
. '-' . $this->name
);
400 wfProfileOut( __METHOD__
);
401 return $status; // invalid storage path
404 if ( $shard !== null ) { // confined to a single container/shard
405 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
406 } else { // directory is on several shards
407 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
408 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
409 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
410 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
414 wfProfileOut( __METHOD__
. '-' . $this->name
);
415 wfProfileOut( __METHOD__
);
420 * @see FileBackendStore::doPrepare()
423 protected function doPrepareInternal( $container, $dir, array $params ) {
424 return Status
::newGood();
428 * @see FileBackend::doSecure()
431 final protected function doSecure( array $params ) {
432 wfProfileIn( __METHOD__
);
433 wfProfileIn( __METHOD__
. '-' . $this->name
);
434 $status = Status
::newGood();
436 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
437 if ( $dir === null ) {
438 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
439 wfProfileOut( __METHOD__
. '-' . $this->name
);
440 wfProfileOut( __METHOD__
);
441 return $status; // invalid storage path
444 if ( $shard !== null ) { // confined to a single container/shard
445 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
446 } else { // directory is on several shards
447 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
448 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
449 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
450 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
454 wfProfileOut( __METHOD__
. '-' . $this->name
);
455 wfProfileOut( __METHOD__
);
460 * @see FileBackendStore::doSecure()
463 protected function doSecureInternal( $container, $dir, array $params ) {
464 return Status
::newGood();
468 * @see FileBackend::doPublish()
471 final protected function doPublish( array $params ) {
472 wfProfileIn( __METHOD__
);
473 wfProfileIn( __METHOD__
. '-' . $this->name
);
474 $status = Status
::newGood();
476 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
477 if ( $dir === null ) {
478 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
479 wfProfileOut( __METHOD__
. '-' . $this->name
);
480 wfProfileOut( __METHOD__
);
481 return $status; // invalid storage path
484 if ( $shard !== null ) { // confined to a single container/shard
485 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
486 } else { // directory is on several shards
487 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
488 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
489 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
490 $status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
494 wfProfileOut( __METHOD__
. '-' . $this->name
);
495 wfProfileOut( __METHOD__
);
500 * @see FileBackendStore::doPublish()
503 protected function doPublishInternal( $container, $dir, array $params ) {
504 return Status
::newGood();
508 * @see FileBackend::doClean()
511 final protected function doClean( array $params ) {
512 wfProfileIn( __METHOD__
);
513 wfProfileIn( __METHOD__
. '-' . $this->name
);
514 $status = Status
::newGood();
516 // Recursive: first delete all empty subdirs recursively
517 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
518 $subDirsRel = $this->getTopDirectoryList( array( 'dir' => $params['dir'] ) );
519 if ( $subDirsRel !== null ) { // no errors
520 foreach ( $subDirsRel as $subDirRel ) {
521 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
522 $status->merge( $this->doClean( array( 'dir' => $subDir ) +
$params ) );
524 unset( $subDirsRel ); // free directory for rmdir() on Windows (for FS backends)
528 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
529 if ( $dir === null ) {
530 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
531 wfProfileOut( __METHOD__
. '-' . $this->name
);
532 wfProfileOut( __METHOD__
);
533 return $status; // invalid storage path
536 // Attempt to lock this directory...
537 $filesLockEx = array( $params['dir'] );
538 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
539 if ( !$status->isOK() ) {
540 wfProfileOut( __METHOD__
. '-' . $this->name
);
541 wfProfileOut( __METHOD__
);
542 return $status; // abort
545 if ( $shard !== null ) { // confined to a single container/shard
546 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
547 $this->deleteContainerCache( $fullCont ); // purge cache
548 } else { // directory is on several shards
549 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
550 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
551 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
552 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
553 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
557 wfProfileOut( __METHOD__
. '-' . $this->name
);
558 wfProfileOut( __METHOD__
);
563 * @see FileBackendStore::doClean()
566 protected function doCleanInternal( $container, $dir, array $params ) {
567 return Status
::newGood();
571 * @see FileBackend::fileExists()
574 final public function fileExists( array $params ) {
575 wfProfileIn( __METHOD__
);
576 wfProfileIn( __METHOD__
. '-' . $this->name
);
577 $stat = $this->getFileStat( $params );
578 wfProfileOut( __METHOD__
. '-' . $this->name
);
579 wfProfileOut( __METHOD__
);
580 return ( $stat === null ) ?
null : (bool)$stat; // null => failure
584 * @see FileBackend::getFileTimestamp()
587 final public function getFileTimestamp( array $params ) {
588 wfProfileIn( __METHOD__
);
589 wfProfileIn( __METHOD__
. '-' . $this->name
);
590 $stat = $this->getFileStat( $params );
591 wfProfileOut( __METHOD__
. '-' . $this->name
);
592 wfProfileOut( __METHOD__
);
593 return $stat ?
$stat['mtime'] : false;
597 * @see FileBackend::getFileSize()
600 final public function getFileSize( array $params ) {
601 wfProfileIn( __METHOD__
);
602 wfProfileIn( __METHOD__
. '-' . $this->name
);
603 $stat = $this->getFileStat( $params );
604 wfProfileOut( __METHOD__
. '-' . $this->name
);
605 wfProfileOut( __METHOD__
);
606 return $stat ?
$stat['size'] : false;
610 * @see FileBackend::getFileStat()
613 final public function getFileStat( array $params ) {
614 $path = self
::normalizeStoragePath( $params['src'] );
615 if ( $path === null ) {
616 return false; // invalid storage path
618 wfProfileIn( __METHOD__
);
619 wfProfileIn( __METHOD__
. '-' . $this->name
);
620 $latest = !empty( $params['latest'] ); // use latest data?
621 if ( !$this->cheapCache
->has( $path, 'stat', self
::CACHE_TTL
) ) {
622 $this->primeFileCache( array( $path ) ); // check persistent cache
624 if ( $this->cheapCache
->has( $path, 'stat', self
::CACHE_TTL
) ) {
625 $stat = $this->cheapCache
->get( $path, 'stat' );
626 // If we want the latest data, check that this cached
627 // value was in fact fetched with the latest available data
628 // (the process cache is ignored if it contains a negative).
629 if ( !$latest ||
( is_array( $stat ) && $stat['latest'] ) ) {
630 wfProfileOut( __METHOD__
. '-' . $this->name
);
631 wfProfileOut( __METHOD__
);
635 wfProfileIn( __METHOD__
. '-miss' );
636 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
637 $stat = $this->doGetFileStat( $params );
638 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
639 wfProfileOut( __METHOD__
. '-miss' );
640 if ( is_array( $stat ) ) { // file exists
641 $stat['latest'] = $latest;
642 $this->cheapCache
->set( $path, 'stat', $stat );
643 $this->setFileCache( $path, $stat ); // update persistent cache
644 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
645 $this->cheapCache
->set( $path, 'sha1',
646 array( 'hash' => $stat['sha1'], 'latest' => $latest ) );
648 } elseif ( $stat === false ) { // file does not exist
649 $this->cheapCache
->set( $path, 'stat', false );
650 wfDebug( __METHOD__
. ": File $path does not exist.\n" );
651 } else { // an error occurred
652 wfDebug( __METHOD__
. ": Could not stat file $path.\n" );
654 wfProfileOut( __METHOD__
. '-' . $this->name
);
655 wfProfileOut( __METHOD__
);
660 * @see FileBackendStore::getFileStat()
662 abstract protected function doGetFileStat( array $params );
665 * @see FileBackend::getFileContentsMulti()
668 public function getFileContentsMulti( array $params ) {
669 wfProfileIn( __METHOD__
);
670 wfProfileIn( __METHOD__
. '-' . $this->name
);
672 $params = $this->setConcurrencyFlags( $params );
673 $contents = $this->doGetFileContentsMulti( $params );
675 wfProfileOut( __METHOD__
. '-' . $this->name
);
676 wfProfileOut( __METHOD__
);
681 * @see FileBackendStore::getFileContentsMulti()
684 protected function doGetFileContentsMulti( array $params ) {
686 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
687 wfSuppressWarnings();
688 $contents[$path] = $fsFile ?
file_get_contents( $fsFile->getPath() ) : false;
695 * @see FileBackend::getFileSha1Base36()
696 * @return bool|string
698 final public function getFileSha1Base36( array $params ) {
699 $path = self
::normalizeStoragePath( $params['src'] );
700 if ( $path === null ) {
701 return false; // invalid storage path
703 wfProfileIn( __METHOD__
);
704 wfProfileIn( __METHOD__
. '-' . $this->name
);
705 $latest = !empty( $params['latest'] ); // use latest data?
706 if ( $this->cheapCache
->has( $path, 'sha1', self
::CACHE_TTL
) ) {
707 $stat = $this->cheapCache
->get( $path, 'sha1' );
708 // If we want the latest data, check that this cached
709 // value was in fact fetched with the latest available data.
710 if ( !$latest ||
$stat['latest'] ) {
711 wfProfileOut( __METHOD__
. '-' . $this->name
);
712 wfProfileOut( __METHOD__
);
713 return $stat['hash'];
716 wfProfileIn( __METHOD__
. '-miss' );
717 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
718 $hash = $this->doGetFileSha1Base36( $params );
719 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
720 wfProfileOut( __METHOD__
. '-miss' );
721 if ( $hash ) { // don't cache negatives
722 $this->cheapCache
->set( $path, 'sha1',
723 array( 'hash' => $hash, 'latest' => $latest ) );
725 wfProfileOut( __METHOD__
. '-' . $this->name
);
726 wfProfileOut( __METHOD__
);
731 * @see FileBackendStore::getFileSha1Base36()
732 * @return bool|string
734 protected function doGetFileSha1Base36( array $params ) {
735 $fsFile = $this->getLocalReference( $params );
739 return $fsFile->getSha1Base36();
744 * @see FileBackend::getFileProps()
747 final public function getFileProps( array $params ) {
748 wfProfileIn( __METHOD__
);
749 wfProfileIn( __METHOD__
. '-' . $this->name
);
750 $fsFile = $this->getLocalReference( $params );
751 $props = $fsFile ?
$fsFile->getProps() : FSFile
::placeholderProps();
752 wfProfileOut( __METHOD__
. '-' . $this->name
);
753 wfProfileOut( __METHOD__
);
758 * @see FileBackend::getLocalReferenceMulti()
761 final public function getLocalReferenceMulti( array $params ) {
762 wfProfileIn( __METHOD__
);
763 wfProfileIn( __METHOD__
. '-' . $this->name
);
765 $params = $this->setConcurrencyFlags( $params );
767 $fsFiles = array(); // (path => FSFile)
768 $latest = !empty( $params['latest'] ); // use latest data?
769 // Reuse any files already in process cache...
770 foreach ( $params['srcs'] as $src ) {
771 $path = self
::normalizeStoragePath( $src );
772 if ( $path === null ) {
773 $fsFiles[$src] = null; // invalid storage path
774 } elseif ( $this->expensiveCache
->has( $path, 'localRef' ) ) {
775 $val = $this->expensiveCache
->get( $path, 'localRef' );
776 // If we want the latest data, check that this cached
777 // value was in fact fetched with the latest available data.
778 if ( !$latest ||
$val['latest'] ) {
779 $fsFiles[$src] = $val['object'];
783 // Fetch local references of any remaning files...
784 $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
785 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
786 $fsFiles[$path] = $fsFile;
787 if ( $fsFile ) { // update the process cache...
788 $this->expensiveCache
->set( $path, 'localRef',
789 array( 'object' => $fsFile, 'latest' => $latest ) );
793 wfProfileOut( __METHOD__
. '-' . $this->name
);
794 wfProfileOut( __METHOD__
);
799 * @see FileBackendStore::getLocalReferenceMulti()
802 protected function doGetLocalReferenceMulti( array $params ) {
803 return $this->doGetLocalCopyMulti( $params );
807 * @see FileBackend::getLocalCopyMulti()
810 final public function getLocalCopyMulti( array $params ) {
811 wfProfileIn( __METHOD__
);
812 wfProfileIn( __METHOD__
. '-' . $this->name
);
814 $params = $this->setConcurrencyFlags( $params );
815 $tmpFiles = $this->doGetLocalCopyMulti( $params );
817 wfProfileOut( __METHOD__
. '-' . $this->name
);
818 wfProfileOut( __METHOD__
);
823 * @see FileBackendStore::getLocalCopyMulti()
826 abstract protected function doGetLocalCopyMulti( array $params );
829 * @see FileBackend::getFileHttpUrl()
830 * @return string|null
832 public function getFileHttpUrl( array $params ) {
833 return null; // not supported
837 * @see FileBackend::streamFile()
840 final public function streamFile( array $params ) {
841 wfProfileIn( __METHOD__
);
842 wfProfileIn( __METHOD__
. '-' . $this->name
);
843 $status = Status
::newGood();
845 $info = $this->getFileStat( $params );
846 if ( !$info ) { // let StreamFile handle the 404
847 $status->fatal( 'backend-fail-notexists', $params['src'] );
850 // Set output buffer and HTTP headers for stream
851 $extraHeaders = isset( $params['headers'] ) ?
$params['headers'] : array();
852 $res = StreamFile
::prepareForStream( $params['src'], $info, $extraHeaders );
853 if ( $res == StreamFile
::NOT_MODIFIED
) {
854 // do nothing; client cache is up to date
855 } elseif ( $res == StreamFile
::READY_STREAM
) {
856 wfProfileIn( __METHOD__
. '-send' );
857 wfProfileIn( __METHOD__
. '-send-' . $this->name
);
858 $status = $this->doStreamFile( $params );
859 wfProfileOut( __METHOD__
. '-send-' . $this->name
);
860 wfProfileOut( __METHOD__
. '-send' );
861 if ( !$status->isOK() ) {
862 // Per bug 41113, nasty things can happen if bad cache entries get
863 // stuck in cache. It's also possible that this error can come up
864 // with simple race conditions. Clear out the stat cache to be safe.
865 $this->clearCache( array( $params['src'] ) );
866 $this->deleteFileCache( $params['src'] );
867 trigger_error( "Bad stat cache or race condition for file {$params['src']}." );
870 $status->fatal( 'backend-fail-stream', $params['src'] );
873 wfProfileOut( __METHOD__
. '-' . $this->name
);
874 wfProfileOut( __METHOD__
);
879 * @see FileBackendStore::streamFile()
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'] );
896 * @see FileBackend::directoryExists()
899 final public function directoryExists( array $params ) {
900 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
901 if ( $dir === null ) {
902 return false; // invalid storage path
904 if ( $shard !== null ) { // confined to a single container/shard
905 return $this->doDirectoryExists( $fullCont, $dir, $params );
906 } else { // directory is on several shards
907 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
908 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
909 $res = false; // response
910 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
911 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
915 } elseif ( $exists === null ) { // error?
916 $res = null; // if we don't find anything, it is indeterminate
924 * @see FileBackendStore::directoryExists()
926 * @param $container string Resolved container name
927 * @param $dir string Resolved path relative to container
928 * @param $params Array
931 abstract protected function doDirectoryExists( $container, $dir, array $params );
934 * @see FileBackend::getDirectoryList()
935 * @return Traversable|Array|null Returns null on failure
937 final public function getDirectoryList( array $params ) {
938 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
939 if ( $dir === null ) { // invalid storage path
942 if ( $shard !== null ) {
943 // File listing is confined to a single container/shard
944 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
946 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
947 // File listing spans multiple containers/shards
948 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
949 return new FileBackendStoreShardDirIterator( $this,
950 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
955 * Do not call this function from places outside FileBackend
957 * @see FileBackendStore::getDirectoryList()
959 * @param $container string Resolved container name
960 * @param $dir string Resolved path relative to container
961 * @param $params Array
962 * @return Traversable|Array|null Returns null on failure
964 abstract public function getDirectoryListInternal( $container, $dir, array $params );
967 * @see FileBackend::getFileList()
968 * @return Traversable|Array|null Returns null on failure
970 final public function getFileList( array $params ) {
971 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
972 if ( $dir === null ) { // invalid storage path
975 if ( $shard !== null ) {
976 // File listing is confined to a single container/shard
977 return $this->getFileListInternal( $fullCont, $dir, $params );
979 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
980 // File listing spans multiple containers/shards
981 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
982 return new FileBackendStoreShardFileIterator( $this,
983 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
988 * Do not call this function from places outside FileBackend
990 * @see FileBackendStore::getFileList()
992 * @param $container string Resolved container name
993 * @param $dir string Resolved path relative to container
994 * @param $params Array
995 * @return Traversable|Array|null Returns null on failure
997 abstract public function getFileListInternal( $container, $dir, array $params );
1000 * Return a list of FileOp objects from a list of operations.
1001 * Do not call this function from places outside FileBackend.
1003 * The result must have the same number of items as the input.
1004 * An exception is thrown if an unsupported operation is requested.
1006 * @param $ops Array Same format as doOperations()
1007 * @return Array List of FileOp objects
1008 * @throws MWException
1010 final public function getOperationsInternal( array $ops ) {
1011 $supportedOps = array(
1012 'store' => 'StoreFileOp',
1013 'copy' => 'CopyFileOp',
1014 'move' => 'MoveFileOp',
1015 'delete' => 'DeleteFileOp',
1016 'create' => 'CreateFileOp',
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 MWException( "Operation '$opName' is not supported." );
1039 * Get a list of storage paths to lock for a list of operations
1040 * Returns an array with 'sh' (shared) and 'ex' (exclusive) keys,
1041 * each corresponding to a list of storage paths to be locked.
1042 * All returned paths are normalized.
1044 * @param $performOps Array List of FileOp objects
1045 * @return Array ('sh' => list of paths, 'ex' => list of paths)
1047 final public function getPathsToLockForOpsInternal( array $performOps ) {
1048 // Build up a list of files to lock...
1049 $paths = array( 'sh' => array(), 'ex' => array() );
1050 foreach ( $performOps as $fileOp ) {
1051 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1052 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1054 // Optimization: if doing an EX lock anyway, don't also set an SH one
1055 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1056 // Get a shared lock on the parent directory of each path changed
1057 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1063 * @see FileBackend::getScopedLocksForOps()
1066 public function getScopedLocksForOps( array $ops, Status
$status ) {
1067 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1069 $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status ),
1070 $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status )
1075 * @see FileBackend::doOperationsInternal()
1078 final protected function doOperationsInternal( array $ops, array $opts ) {
1079 wfProfileIn( __METHOD__
);
1080 wfProfileIn( __METHOD__
. '-' . $this->name
);
1081 $status = Status
::newGood();
1083 // Build up a list of FileOps...
1084 $performOps = $this->getOperationsInternal( $ops );
1086 // Acquire any locks as needed...
1087 if ( empty( $opts['nonLocking'] ) ) {
1088 // Build up a list of files to lock...
1089 $paths = $this->getPathsToLockForOpsInternal( $performOps );
1090 // Try to lock those files for the scope of this function...
1091 $scopeLockS = $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status );
1092 $scopeLockE = $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status );
1093 if ( !$status->isOK() ) {
1094 wfProfileOut( __METHOD__
. '-' . $this->name
);
1095 wfProfileOut( __METHOD__
);
1096 return $status; // abort
1100 // Clear any file cache entries (after locks acquired)
1101 if ( empty( $opts['preserveCache'] ) ) {
1102 $this->clearCache();
1105 // Load from the persistent file and container caches
1106 $this->primeFileCache( $performOps );
1107 $this->primeContainerCache( $performOps );
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()
1117 wfProfileOut( __METHOD__
. '-' . $this->name
);
1118 wfProfileOut( __METHOD__
);
1123 * @see FileBackend::doQuickOperationsInternal()
1125 * @throws MWException
1127 final protected function doQuickOperationsInternal( array $ops ) {
1128 wfProfileIn( __METHOD__
);
1129 wfProfileIn( __METHOD__
. '-' . $this->name
);
1130 $status = Status
::newGood();
1132 $supportedOps = array( 'create', 'store', 'copy', 'move', 'delete', 'null' );
1133 $async = ( $this->parallelize
=== 'implicit' );
1134 $maxConcurrency = $this->concurrency
; // throttle
1136 $statuses = array(); // array of (index => Status)
1137 $fileOpHandles = array(); // list of (index => handle) arrays
1138 $curFileOpHandles = array(); // current handle batch
1139 // Perform the sync-only ops and build up op handles for the async ops...
1140 foreach ( $ops as $index => $params ) {
1141 if ( !in_array( $params['op'], $supportedOps ) ) {
1142 wfProfileOut( __METHOD__
. '-' . $this->name
);
1143 wfProfileOut( __METHOD__
);
1144 throw new MWException( "Operation '{$params['op']}' is not supported." );
1146 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1147 $subStatus = $this->$method( array( 'async' => $async ) +
$params );
1148 if ( $subStatus->value
instanceof FileBackendStoreOpHandle
) { // async
1149 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1150 $fileOpHandles[] = $curFileOpHandles; // push this batch
1151 $curFileOpHandles = array();
1153 $curFileOpHandles[$index] = $subStatus->value
; // keep index
1154 } else { // error or completed
1155 $statuses[$index] = $subStatus; // keep index
1158 if ( count( $curFileOpHandles ) ) {
1159 $fileOpHandles[] = $curFileOpHandles; // last batch
1161 // Do all the async ops that can be done concurrently...
1162 foreach ( $fileOpHandles as $fileHandleBatch ) {
1163 $statuses = $statuses +
$this->executeOpHandlesInternal( $fileHandleBatch );
1165 // Marshall and merge all the responses...
1166 foreach ( $statuses as $index => $subStatus ) {
1167 $status->merge( $subStatus );
1168 if ( $subStatus->isOK() ) {
1169 $status->success
[$index] = true;
1170 ++
$status->successCount
;
1172 $status->success
[$index] = false;
1173 ++
$status->failCount
;
1177 wfProfileOut( __METHOD__
. '-' . $this->name
);
1178 wfProfileOut( __METHOD__
);
1183 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1184 * The resulting Status object fields will correspond
1185 * to the order in which the handles where given.
1187 * @param $handles Array List of FileBackendStoreOpHandle objects
1188 * @return Array Map of Status objects
1189 * @throws MWException
1191 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1192 wfProfileIn( __METHOD__
);
1193 wfProfileIn( __METHOD__
. '-' . $this->name
);
1194 foreach ( $fileOpHandles as $fileOpHandle ) {
1195 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle
) ) {
1196 throw new MWException( "Given a non-FileBackendStoreOpHandle object." );
1197 } elseif ( $fileOpHandle->backend
->getName() !== $this->getName() ) {
1198 throw new MWException( "Given a FileBackendStoreOpHandle for the wrong backend." );
1201 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1202 foreach ( $fileOpHandles as $fileOpHandle ) {
1203 $fileOpHandle->closeResources();
1205 wfProfileOut( __METHOD__
. '-' . $this->name
);
1206 wfProfileOut( __METHOD__
);
1211 * @see FileBackendStore::executeOpHandlesInternal()
1212 * @param array $fileOpHandles
1213 * @throws MWException
1214 * @return Array List of corresponding Status objects
1216 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1217 foreach ( $fileOpHandles as $fileOpHandle ) { // OK if empty
1218 throw new MWException( "This backend supports no asynchronous operations." );
1224 * @see FileBackend::preloadCache()
1226 final public function preloadCache( array $paths ) {
1227 $fullConts = array(); // full container names
1228 foreach ( $paths as $path ) {
1229 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1230 $fullConts[] = $fullCont;
1232 // Load from the persistent file and container caches
1233 $this->primeContainerCache( $fullConts );
1234 $this->primeFileCache( $paths );
1238 * @see FileBackend::clearCache()
1240 final public function clearCache( array $paths = null ) {
1241 if ( is_array( $paths ) ) {
1242 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1243 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1245 if ( $paths === null ) {
1246 $this->cheapCache
->clear();
1247 $this->expensiveCache
->clear();
1249 foreach ( $paths as $path ) {
1250 $this->cheapCache
->clear( $path );
1251 $this->expensiveCache
->clear( $path );
1254 $this->doClearCache( $paths );
1258 * Clears any additional stat caches for storage paths
1260 * @see FileBackend::clearCache()
1262 * @param $paths Array Storage paths (optional)
1265 protected function doClearCache( array $paths = null ) {}
1268 * Is this a key/value store where directories are just virtual?
1269 * Virtual directories exists in so much as files exists that are
1270 * prefixed with the directory path followed by a forward slash.
1274 abstract protected function directoriesAreVirtual();
1277 * Check if a container name is valid.
1278 * This checks for for length and illegal characters.
1280 * @param $container string
1283 final protected static function isValidContainerName( $container ) {
1284 // This accounts for Swift and S3 restrictions while leaving room
1285 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1286 // This disallows directory separators or traversal characters.
1287 // Note that matching strings URL encode to the same string;
1288 // in Swift, the length restriction is *after* URL encoding.
1289 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1293 * Splits a storage path into an internal container name,
1294 * an internal relative file name, and a container shard suffix.
1295 * Any shard suffix is already appended to the internal container name.
1296 * This also checks that the storage path is valid and within this backend.
1298 * If the container is sharded but a suffix could not be determined,
1299 * this means that the path can only refer to a directory and can only
1300 * be scanned by looking in all the container shards.
1302 * @param $storagePath string
1303 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1305 final protected function resolveStoragePath( $storagePath ) {
1306 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1307 if ( $backend === $this->name
) { // must be for this backend
1308 $relPath = self
::normalizeContainerPath( $relPath );
1309 if ( $relPath !== null ) {
1310 // Get shard for the normalized path if this container is sharded
1311 $cShard = $this->getContainerShard( $container, $relPath );
1312 // Validate and sanitize the relative path (backend-specific)
1313 $relPath = $this->resolveContainerPath( $container, $relPath );
1314 if ( $relPath !== null ) {
1315 // Prepend any wiki ID prefix to the container name
1316 $container = $this->fullContainerName( $container );
1317 if ( self
::isValidContainerName( $container ) ) {
1318 // Validate and sanitize the container name (backend-specific)
1319 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1320 if ( $container !== null ) {
1321 return array( $container, $relPath, $cShard );
1327 return array( null, null, null );
1331 * Like resolveStoragePath() except null values are returned if
1332 * the container is sharded and the shard could not be determined.
1334 * @see FileBackendStore::resolveStoragePath()
1336 * @param $storagePath string
1337 * @return Array (container, path) or (null, null) if invalid
1339 final protected function resolveStoragePathReal( $storagePath ) {
1340 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1341 if ( $cShard !== null ) {
1342 return array( $container, $relPath );
1344 return array( null, null );
1348 * Get the container name shard suffix for a given path.
1349 * Any empty suffix means the container is not sharded.
1351 * @param $container string Container name
1352 * @param $relPath string Storage path relative to the container
1353 * @return string|null Returns null if shard could not be determined
1355 final protected function getContainerShard( $container, $relPath ) {
1356 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1357 if ( $levels == 1 ||
$levels == 2 ) {
1358 // Hash characters are either base 16 or 36
1359 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1360 // Get a regex that represents the shard portion of paths.
1361 // The concatenation of the captures gives us the shard.
1362 if ( $levels === 1 ) { // 16 or 36 shards per container
1363 $hashDirRegex = '(' . $char . ')';
1364 } else { // 256 or 1296 shards per container
1365 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1366 $hashDirRegex = $char . '/(' . $char . '{2})';
1367 } else { // short hash dir format (e.g. "a/b/c")
1368 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1371 // Allow certain directories to be above the hash dirs so as
1372 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1373 // They must be 2+ chars to avoid any hash directory ambiguity.
1375 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1376 return '.' . implode( '', array_slice( $m, 1 ) );
1378 return null; // failed to match
1380 return ''; // no sharding
1384 * Check if a storage path maps to a single shard.
1385 * Container dirs like "a", where the container shards on "x/xy",
1386 * can reside on several shards. Such paths are tricky to handle.
1388 * @param $storagePath string Storage path
1391 final public function isSingleShardPathInternal( $storagePath ) {
1392 list( $c, $r, $shard ) = $this->resolveStoragePath( $storagePath );
1393 return ( $shard !== null );
1397 * Get the sharding config for a container.
1398 * If greater than 0, then all file storage paths within
1399 * the container are required to be hashed accordingly.
1401 * @param $container string
1402 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
1404 final protected function getContainerHashLevels( $container ) {
1405 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1406 $config = $this->shardViaHashLevels
[$container];
1407 $hashLevels = (int)$config['levels'];
1408 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1409 $hashBase = (int)$config['base'];
1410 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1411 return array( $hashLevels, $hashBase, $config['repeat'] );
1415 return array( 0, 0, false ); // no sharding
1419 * Get a list of full container shard suffixes for a container
1421 * @param $container string
1424 final protected function getContainerSuffixes( $container ) {
1426 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1427 if ( $digits > 0 ) {
1428 $numShards = pow( $base, $digits );
1429 for ( $index = 0; $index < $numShards; $index++
) {
1430 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1437 * Get the full container name, including the wiki ID prefix
1439 * @param $container string
1442 final protected function fullContainerName( $container ) {
1443 if ( $this->wikiId
!= '' ) {
1444 return "{$this->wikiId}-$container";
1451 * Resolve a container name, checking if it's allowed by the backend.
1452 * This is intended for internal use, such as encoding illegal chars.
1453 * Subclasses can override this to be more restrictive.
1455 * @param $container string
1456 * @return string|null
1458 protected function resolveContainerName( $container ) {
1463 * Resolve a relative storage path, checking if it's allowed by the backend.
1464 * This is intended for internal use, such as encoding illegal chars or perhaps
1465 * getting absolute paths (e.g. FS based backends). Note that the relative path
1466 * may be the empty string (e.g. the path is simply to the container).
1468 * @param $container string Container name
1469 * @param $relStoragePath string Storage path relative to the container
1470 * @return string|null Path or null if not valid
1472 protected function resolveContainerPath( $container, $relStoragePath ) {
1473 return $relStoragePath;
1477 * Get the cache key for a container
1479 * @param $container string Resolved container name
1482 private function containerCacheKey( $container ) {
1483 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1487 * Set the cached info for a container
1489 * @param $container string Resolved container name
1490 * @param $val mixed Information to cache
1492 final protected function setContainerCache( $container, $val ) {
1493 $this->memCache
->add( $this->containerCacheKey( $container ), $val, 14*86400 );
1497 * Delete the cached info for a container.
1498 * The cache key is salted for a while to prevent race conditions.
1500 * @param $container string Resolved container name
1502 final protected function deleteContainerCache( $container ) {
1503 if ( !$this->memCache
->set( $this->containerCacheKey( $container ), 'PURGED', 300 ) ) {
1504 trigger_error( "Unable to delete stat cache for container $container." );
1509 * Do a batch lookup from cache for container stats for all containers
1510 * used in a list of container names, storage paths, or FileOp objects.
1511 * This loads the persistent cache values into the process cache.
1513 * @param $items Array
1516 final protected function primeContainerCache( array $items ) {
1517 wfProfileIn( __METHOD__
);
1518 wfProfileIn( __METHOD__
. '-' . $this->name
);
1520 $paths = array(); // list of storage paths
1521 $contNames = array(); // (cache key => resolved container name)
1522 // Get all the paths/containers from the items...
1523 foreach ( $items as $item ) {
1524 if ( $item instanceof FileOp
) {
1525 $paths = array_merge( $paths, $item->storagePathsRead() );
1526 $paths = array_merge( $paths, $item->storagePathsChanged() );
1527 } elseif ( self
::isStoragePath( $item ) ) {
1529 } elseif ( is_string( $item ) ) { // full container name
1530 $contNames[$this->containerCacheKey( $item )] = $item;
1533 // Get all the corresponding cache keys for paths...
1534 foreach ( $paths as $path ) {
1535 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1536 if ( $fullCont !== null ) { // valid path for this backend
1537 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1541 $contInfo = array(); // (resolved container name => cache value)
1542 // Get all cache entries for these container cache keys...
1543 $values = $this->memCache
->getMulti( array_keys( $contNames ) );
1544 foreach ( $values as $cacheKey => $val ) {
1545 $contInfo[$contNames[$cacheKey]] = $val;
1548 // Populate the container process cache for the backend...
1549 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1551 wfProfileOut( __METHOD__
. '-' . $this->name
);
1552 wfProfileOut( __METHOD__
);
1556 * Fill the backend-specific process cache given an array of
1557 * resolved container names and their corresponding cached info.
1558 * Only containers that actually exist should appear in the map.
1560 * @param $containerInfo Array Map of resolved container names to cached info
1563 protected function doPrimeContainerCache( array $containerInfo ) {}
1566 * Get the cache key for a file path
1568 * @param $path string Normalized storage path
1571 private function fileCacheKey( $path ) {
1572 return wfMemcKey( 'backend', $this->getName(), 'file', sha1( $path ) );
1576 * Set the cached stat info for a file path.
1577 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1578 * salting for the case when a file is created at a path were there was none before.
1580 * @param $path string Storage path
1581 * @param $val mixed Information to cache
1583 final protected function setFileCache( $path, $val ) {
1584 $path = FileBackend
::normalizeStoragePath( $path );
1585 if ( $path === null ) {
1586 return; // invalid storage path
1588 $this->memCache
->add( $this->fileCacheKey( $path ), $val, 7*86400 );
1592 * Delete the cached stat info for a file path.
1593 * The cache key is salted for a while to prevent race conditions.
1595 * @param $path string Storage path
1597 final protected function deleteFileCache( $path ) {
1598 $path = FileBackend
::normalizeStoragePath( $path );
1599 if ( $path === null ) {
1600 return; // invalid storage path
1602 if ( !$this->memCache
->set( $this->fileCacheKey( $path ), 'PURGED', 300 ) ) {
1603 trigger_error( "Unable to delete stat cache for file $path." );
1608 * Do a batch lookup from cache for file stats for all paths
1609 * used in a list of storage paths or FileOp objects.
1610 * This loads the persistent cache values into the process cache.
1612 * @param $items Array List of storage paths or FileOps
1615 final protected function primeFileCache( array $items ) {
1616 wfProfileIn( __METHOD__
);
1617 wfProfileIn( __METHOD__
. '-' . $this->name
);
1619 $paths = array(); // list of storage paths
1620 $pathNames = array(); // (cache key => storage path)
1621 // Get all the paths/containers from the items...
1622 foreach ( $items as $item ) {
1623 if ( $item instanceof FileOp
) {
1624 $paths = array_merge( $paths, $item->storagePathsRead() );
1625 $paths = array_merge( $paths, $item->storagePathsChanged() );
1626 } elseif ( self
::isStoragePath( $item ) ) {
1627 $paths[] = FileBackend
::normalizeStoragePath( $item );
1630 // Get rid of any paths that failed normalization...
1631 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1632 // Get all the corresponding cache keys for paths...
1633 foreach ( $paths as $path ) {
1634 list( $cont, $rel, $s ) = $this->resolveStoragePath( $path );
1635 if ( $rel !== null ) { // valid path for this backend
1636 $pathNames[$this->fileCacheKey( $path )] = $path;
1639 // Get all cache entries for these container cache keys...
1640 $values = $this->memCache
->getMulti( array_keys( $pathNames ) );
1641 foreach ( $values as $cacheKey => $val ) {
1642 if ( is_array( $val ) ) {
1643 $path = $pathNames[$cacheKey];
1644 $this->cheapCache
->set( $path, 'stat', $val );
1645 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1646 $this->cheapCache
->set( $path, 'sha1',
1647 array( 'hash' => $val['sha1'], 'latest' => $val['latest'] ) );
1652 wfProfileOut( __METHOD__
. '-' . $this->name
);
1653 wfProfileOut( __METHOD__
);
1657 * Set the 'concurrency' option from a list of operation options
1659 * @param $opts array Map of operation options
1662 final protected function setConcurrencyFlags( array $opts ) {
1663 $opts['concurrency'] = 1; // off
1664 if ( $this->parallelize
=== 'implicit' ) {
1665 if ( !isset( $opts['parallelize'] ) ||
$opts['parallelize'] ) {
1666 $opts['concurrency'] = $this->concurrency
;
1668 } elseif ( $this->parallelize
=== 'explicit' ) {
1669 if ( !empty( $opts['parallelize'] ) ) {
1670 $opts['concurrency'] = $this->concurrency
;
1678 * FileBackendStore helper class for performing asynchronous file operations.
1680 * For example, calling FileBackendStore::createInternal() with the "async"
1681 * param flag may result in a Status that contains this object as a value.
1682 * This class is largely backend-specific and is mostly just "magic" to be
1683 * passed to FileBackendStore::executeOpHandlesInternal().
1685 abstract class FileBackendStoreOpHandle
{
1687 public $params = array(); // params to caller functions
1688 /** @var FileBackendStore */
1691 public $resourcesToClose = array();
1693 public $call; // string; name that identifies the function called
1696 * Close all open file handles
1700 public function closeResources() {
1701 array_map( 'fclose', $this->resourcesToClose
);
1706 * FileBackendStore helper function to handle listings that span container shards.
1707 * Do not use this class from places outside of FileBackendStore.
1709 * @ingroup FileBackend
1711 abstract class FileBackendStoreShardListIterator
implements Iterator
{
1712 /** @var FileBackendStore */
1717 protected $shardSuffixes;
1718 protected $container; // string; full container name
1719 protected $directory; // string; resolved relative path
1721 /** @var Traversable */
1723 protected $curShard = 0; // integer
1724 protected $pos = 0; // integer
1727 protected $multiShardPaths = array(); // (rel path => 1)
1730 * @param $backend FileBackendStore
1731 * @param $container string Full storage container name
1732 * @param $dir string Storage directory relative to container
1733 * @param $suffixes Array List of container shard suffixes
1734 * @param $params Array
1736 public function __construct(
1737 FileBackendStore
$backend, $container, $dir, array $suffixes, array $params
1739 $this->backend
= $backend;
1740 $this->container
= $container;
1741 $this->directory
= $dir;
1742 $this->shardSuffixes
= $suffixes;
1743 $this->params
= $params;
1747 * @see Iterator::key()
1750 public function key() {
1755 * @see Iterator::valid()
1758 public function valid() {
1759 if ( $this->iter
instanceof Iterator
) {
1760 return $this->iter
->valid();
1761 } elseif ( is_array( $this->iter
) ) {
1762 return ( current( $this->iter
) !== false ); // no paths can have this value
1764 return false; // some failure?
1768 * @see Iterator::current()
1769 * @return string|bool String or false
1771 public function current() {
1772 return ( $this->iter
instanceof Iterator
)
1773 ?
$this->iter
->current()
1774 : current( $this->iter
);
1778 * @see Iterator::next()
1781 public function next() {
1783 ( $this->iter
instanceof Iterator
) ?
$this->iter
->next() : next( $this->iter
);
1785 $continue = false; // keep scanning shards?
1786 $this->filterViaNext(); // filter out duplicates
1787 // Find the next non-empty shard if no elements are left
1788 if ( !$this->valid() ) {
1789 $this->nextShardIteratorIfNotValid();
1790 $continue = $this->valid(); // re-filter unless we ran out of shards
1792 } while ( $continue );
1796 * @see Iterator::rewind()
1799 public function rewind() {
1801 $this->curShard
= 0;
1802 $this->setIteratorFromCurrentShard();
1804 $continue = false; // keep scanning shards?
1805 $this->filterViaNext(); // filter out duplicates
1806 // Find the next non-empty shard if no elements are left
1807 if ( !$this->valid() ) {
1808 $this->nextShardIteratorIfNotValid();
1809 $continue = $this->valid(); // re-filter unless we ran out of shards
1811 } while ( $continue );
1815 * Filter out duplicate items by advancing to the next ones
1817 protected function filterViaNext() {
1818 while ( $this->valid() ) {
1819 $rel = $this->iter
->current(); // path relative to given directory
1820 $path = $this->params
['dir'] . "/{$rel}"; // full storage path
1821 if ( $this->backend
->isSingleShardPathInternal( $path ) ) {
1822 break; // path is only on one shard; no issue with duplicates
1823 } elseif ( isset( $this->multiShardPaths
[$rel] ) ) {
1824 // Don't keep listing paths that are on multiple shards
1825 ( $this->iter
instanceof Iterator
) ?
$this->iter
->next() : next( $this->iter
);
1827 $this->multiShardPaths
[$rel] = 1;
1834 * If the list iterator for this container shard is out of items,
1835 * then move on to the next container that has items.
1836 * If there are none, then it advances to the last container.
1838 protected function nextShardIteratorIfNotValid() {
1839 while ( !$this->valid() && ++
$this->curShard
< count( $this->shardSuffixes
) ) {
1840 $this->setIteratorFromCurrentShard();
1845 * Set the list iterator to that of the current container shard
1847 protected function setIteratorFromCurrentShard() {
1848 $this->iter
= $this->listFromShard(
1849 $this->container
. $this->shardSuffixes
[$this->curShard
],
1850 $this->directory
, $this->params
);
1851 // Start loading results so that current() works
1852 if ( $this->iter
) {
1853 ( $this->iter
instanceof Iterator
) ?
$this->iter
->rewind() : reset( $this->iter
);
1858 * Get the list for a given container shard
1860 * @param $container string Resolved container name
1861 * @param $dir string Resolved path relative to container
1862 * @param $params Array
1863 * @return Traversable|Array|null
1865 abstract protected function listFromShard( $container, $dir, array $params );
1869 * Iterator for listing directories
1871 class FileBackendStoreShardDirIterator
extends FileBackendStoreShardListIterator
{
1873 * @see FileBackendStoreShardListIterator::listFromShard()
1874 * @return Array|null|Traversable
1876 protected function listFromShard( $container, $dir, array $params ) {
1877 return $this->backend
->getDirectoryListInternal( $container, $dir, $params );
1882 * Iterator for listing regular files
1884 class FileBackendStoreShardFileIterator
extends FileBackendStoreShardListIterator
{
1886 * @see FileBackendStoreShardListIterator::listFromShard()
1887 * @return Array|null|Traversable
1889 protected function listFromShard( $container, $dir, array $params ) {
1890 return $this->backend
->getFileListInternal( $container, $dir, $params );