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
52 const CACHE_CHEAP_SIZE
= 300; // integer; max entries in "cheap cache"
53 const CACHE_EXPENSIVE_SIZE
= 5; // integer; max entries in "expensive cache"
56 * @see FileBackend::__construct()
58 * @param array $config
60 public function __construct( array $config ) {
61 parent
::__construct( $config );
62 $this->memCache
= new EmptyBagOStuff(); // disabled by default
63 $this->cheapCache
= new ProcessCacheLRU( self
::CACHE_CHEAP_SIZE
);
64 $this->expensiveCache
= new ProcessCacheLRU( self
::CACHE_EXPENSIVE_SIZE
);
68 * Get the maximum allowable file size given backend
69 * medium restrictions and basic performance constraints.
70 * Do not call this function from places outside FileBackend and FileOp.
72 * @return integer Bytes
74 final public function maxFileSizeInternal() {
75 return $this->maxFileSize
;
79 * Check if a file can be created or changed at a given storage path.
80 * FS backends should check if the parent directory exists, files can be
81 * written under it, and that any file already there is writable.
82 * Backends using key/value stores should check if the container exists.
84 * @param string $storagePath
87 abstract public function isPathUsableInternal( $storagePath );
90 * Create a file in the backend with the given contents.
91 * This will overwrite any file that exists at the destination.
92 * Do not call this function from places outside FileBackend and FileOp.
95 * - content : the raw file contents
96 * - dst : destination storage path
97 * - headers : HTTP header name/value map
98 * - async : Status will be returned immediately if supported.
99 * If the status is OK, then its value field will be
100 * set to a FileBackendStoreOpHandle object.
101 * - dstExists : Whether a file exists at the destination (optimization).
102 * Callers can use "false" if no existing file is being changed.
104 * @param array $params
107 final public function createInternal( array $params ) {
108 wfProfileIn( __METHOD__
);
109 wfProfileIn( __METHOD__
. '-' . $this->name
);
110 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
111 $status = Status
::newFatal( 'backend-fail-maxsize',
112 $params['dst'], $this->maxFileSizeInternal() );
114 $status = $this->doCreateInternal( $params );
115 $this->clearCache( array( $params['dst'] ) );
116 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
117 $this->deleteFileCache( $params['dst'] ); // persistent cache
120 wfProfileOut( __METHOD__
. '-' . $this->name
);
121 wfProfileOut( __METHOD__
);
126 * @see FileBackendStore::createInternal()
129 abstract protected function doCreateInternal( array $params );
132 * Store a file into the backend from a file on disk.
133 * This will overwrite any file that exists at the destination.
134 * Do not call this function from places outside FileBackend and FileOp.
137 * - src : source path on disk
138 * - dst : destination storage path
139 * - headers : HTTP header name/value map
140 * - async : Status will be returned immediately if supported.
141 * If the status is OK, then its value field will be
142 * set to a FileBackendStoreOpHandle object.
143 * - dstExists : Whether a file exists at the destination (optimization).
144 * Callers can use "false" if no existing file is being changed.
146 * @param array $params
149 final public function storeInternal( array $params ) {
150 wfProfileIn( __METHOD__
);
151 wfProfileIn( __METHOD__
. '-' . $this->name
);
152 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
153 $status = Status
::newFatal( 'backend-fail-maxsize',
154 $params['dst'], $this->maxFileSizeInternal() );
156 $status = $this->doStoreInternal( $params );
157 $this->clearCache( array( $params['dst'] ) );
158 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
159 $this->deleteFileCache( $params['dst'] ); // persistent cache
162 wfProfileOut( __METHOD__
. '-' . $this->name
);
163 wfProfileOut( __METHOD__
);
168 * @see FileBackendStore::storeInternal()
171 abstract protected function doStoreInternal( array $params );
174 * Copy a file from one storage path to another in the backend.
175 * This will overwrite any file that exists at the destination.
176 * Do not call this function from places outside FileBackend and FileOp.
179 * - src : source storage path
180 * - dst : destination storage path
181 * - ignoreMissingSource : do nothing if the source file does not exist
182 * - headers : HTTP header name/value map
183 * - async : Status will be returned immediately if supported.
184 * If the status is OK, then its value field will be
185 * set to a FileBackendStoreOpHandle object.
186 * - dstExists : Whether a file exists at the destination (optimization).
187 * Callers can use "false" if no existing file is being changed.
189 * @param array $params
192 final public function copyInternal( array $params ) {
193 wfProfileIn( __METHOD__
);
194 wfProfileIn( __METHOD__
. '-' . $this->name
);
195 $status = $this->doCopyInternal( $params );
196 $this->clearCache( array( $params['dst'] ) );
197 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
198 $this->deleteFileCache( $params['dst'] ); // persistent cache
200 wfProfileOut( __METHOD__
. '-' . $this->name
);
201 wfProfileOut( __METHOD__
);
206 * @see FileBackendStore::copyInternal()
209 abstract protected function doCopyInternal( array $params );
212 * Delete a file at the storage path.
213 * Do not call this function from places outside FileBackend and FileOp.
216 * - src : source storage path
217 * - ignoreMissingSource : do nothing if the source file does not exist
218 * - async : Status will be returned immediately if supported.
219 * If the status is OK, then its value field will be
220 * set to a FileBackendStoreOpHandle object.
222 * @param array $params
225 final public function deleteInternal( array $params ) {
226 wfProfileIn( __METHOD__
);
227 wfProfileIn( __METHOD__
. '-' . $this->name
);
228 $status = $this->doDeleteInternal( $params );
229 $this->clearCache( array( $params['src'] ) );
230 $this->deleteFileCache( $params['src'] ); // persistent cache
231 wfProfileOut( __METHOD__
. '-' . $this->name
);
232 wfProfileOut( __METHOD__
);
237 * @see FileBackendStore::deleteInternal()
240 abstract protected function doDeleteInternal( array $params );
243 * Move a file from one storage path to another in the backend.
244 * This will overwrite any file that exists at the destination.
245 * Do not call this function from places outside FileBackend and FileOp.
248 * - src : source storage path
249 * - dst : destination storage path
250 * - ignoreMissingSource : do nothing if the source file does not exist
251 * - headers : HTTP header name/value map
252 * - async : Status will be returned immediately if supported.
253 * If the status is OK, then its value field will be
254 * set to a FileBackendStoreOpHandle object.
255 * - dstExists : Whether a file exists at the destination (optimization).
256 * Callers can use "false" if no existing file is being changed.
258 * @param array $params
261 final public function moveInternal( array $params ) {
262 wfProfileIn( __METHOD__
);
263 wfProfileIn( __METHOD__
. '-' . $this->name
);
264 $status = $this->doMoveInternal( $params );
265 $this->clearCache( array( $params['src'], $params['dst'] ) );
266 $this->deleteFileCache( $params['src'] ); // persistent cache
267 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
268 $this->deleteFileCache( $params['dst'] ); // persistent cache
270 wfProfileOut( __METHOD__
. '-' . $this->name
);
271 wfProfileOut( __METHOD__
);
276 * @see FileBackendStore::moveInternal()
279 protected function doMoveInternal( array $params ) {
280 unset( $params['async'] ); // two steps, won't work here :)
281 $nsrc = FileBackend
::normalizeStoragePath( $params['src'] );
282 $ndst = FileBackend
::normalizeStoragePath( $params['dst'] );
283 // Copy source to dest
284 $status = $this->copyInternal( $params );
285 if ( $nsrc !== $ndst && $status->isOK() ) {
286 // Delete source (only fails due to races or network problems)
287 $status->merge( $this->deleteInternal( array( 'src' => $params['src'] ) ) );
288 $status->setResult( true, $status->value
); // ignore delete() errors
294 * Alter metadata for a file at the storage path.
295 * Do not call this function from places outside FileBackend and FileOp.
298 * - src : source storage path
299 * - headers : HTTP header name/value map
300 * - async : Status will be returned immediately if supported.
301 * If the status is OK, then its value field will be
302 * set to a FileBackendStoreOpHandle object.
304 * @param array $params
307 final public function describeInternal( array $params ) {
308 wfProfileIn( __METHOD__
);
309 wfProfileIn( __METHOD__
. '-' . $this->name
);
310 if ( count( $params['headers'] ) ) {
311 $status = $this->doDescribeInternal( $params );
312 $this->clearCache( array( $params['src'] ) );
313 $this->deleteFileCache( $params['src'] ); // persistent cache
315 $status = Status
::newGood(); // nothing to do
317 wfProfileOut( __METHOD__
. '-' . $this->name
);
318 wfProfileOut( __METHOD__
);
323 * @see FileBackendStore::describeInternal()
326 protected function doDescribeInternal( array $params ) {
327 return Status
::newGood();
331 * No-op file operation that does nothing.
332 * Do not call this function from places outside FileBackend and FileOp.
334 * @param array $params
337 final public function nullInternal( array $params ) {
338 return Status
::newGood();
341 final public function concatenate( array $params ) {
342 wfProfileIn( __METHOD__
);
343 wfProfileIn( __METHOD__
. '-' . $this->name
);
344 $status = Status
::newGood();
346 // Try to lock the source files for the scope of this function
347 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager
::LOCK_UW
, $status );
348 if ( $status->isOK() ) {
349 // Actually do the file concatenation...
350 $start_time = microtime( true );
351 $status->merge( $this->doConcatenate( $params ) );
352 $sec = microtime( true ) - $start_time;
353 if ( !$status->isOK() ) {
354 wfDebugLog( 'FileOperation', get_class( $this ) . " failed to concatenate " .
355 count( $params['srcs'] ) . " file(s) [$sec sec]" );
359 wfProfileOut( __METHOD__
. '-' . $this->name
);
360 wfProfileOut( __METHOD__
);
365 * @see FileBackendStore::concatenate()
368 protected function doConcatenate( array $params ) {
369 $status = Status
::newGood();
370 $tmpPath = $params['dst']; // convenience
371 unset( $params['latest'] ); // sanity
373 // Check that the specified temp file is valid...
374 wfSuppressWarnings();
375 $ok = ( is_file( $tmpPath ) && filesize( $tmpPath ) == 0 );
377 if ( !$ok ) { // not present or not empty
378 $status->fatal( 'backend-fail-opentemp', $tmpPath );
382 // Get local FS versions of the chunks needed for the concatenation...
383 $fsFiles = $this->getLocalReferenceMulti( $params );
384 foreach ( $fsFiles as $path => &$fsFile ) {
385 if ( !$fsFile ) { // chunk failed to download?
386 $fsFile = $this->getLocalReference( array( 'src' => $path ) );
387 if ( !$fsFile ) { // retry failed?
388 $status->fatal( 'backend-fail-read', $path );
393 unset( $fsFile ); // unset reference so we can reuse $fsFile
395 // Get a handle for the destination temp file
396 $tmpHandle = fopen( $tmpPath, 'ab' );
397 if ( $tmpHandle === false ) {
398 $status->fatal( 'backend-fail-opentemp', $tmpPath );
402 // Build up the temp file using the source chunks (in order)...
403 foreach ( $fsFiles as $virtualSource => $fsFile ) {
404 // Get a handle to the local FS version
405 $sourceHandle = fopen( $fsFile->getPath(), 'rb' );
406 if ( $sourceHandle === false ) {
407 fclose( $tmpHandle );
408 $status->fatal( 'backend-fail-read', $virtualSource );
411 // Append chunk to file (pass chunk size to avoid magic quotes)
412 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
413 fclose( $sourceHandle );
414 fclose( $tmpHandle );
415 $status->fatal( 'backend-fail-writetemp', $tmpPath );
418 fclose( $sourceHandle );
420 if ( !fclose( $tmpHandle ) ) {
421 $status->fatal( 'backend-fail-closetemp', $tmpPath );
425 clearstatcache(); // temp file changed
430 final protected function doPrepare( array $params ) {
431 wfProfileIn( __METHOD__
);
432 wfProfileIn( __METHOD__
. '-' . $this->name
);
434 $status = Status
::newGood();
435 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
436 if ( $dir === null ) {
437 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
438 wfProfileOut( __METHOD__
. '-' . $this->name
);
439 wfProfileOut( __METHOD__
);
440 return $status; // invalid storage path
443 if ( $shard !== null ) { // confined to a single container/shard
444 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
445 } else { // directory is on several shards
446 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
447 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
448 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
449 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
453 wfProfileOut( __METHOD__
. '-' . $this->name
);
454 wfProfileOut( __METHOD__
);
459 * @see FileBackendStore::doPrepare()
462 protected function doPrepareInternal( $container, $dir, array $params ) {
463 return Status
::newGood();
466 final protected function doSecure( array $params ) {
467 wfProfileIn( __METHOD__
);
468 wfProfileIn( __METHOD__
. '-' . $this->name
);
469 $status = Status
::newGood();
471 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
472 if ( $dir === null ) {
473 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
474 wfProfileOut( __METHOD__
. '-' . $this->name
);
475 wfProfileOut( __METHOD__
);
476 return $status; // invalid storage path
479 if ( $shard !== null ) { // confined to a single container/shard
480 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
481 } else { // directory is on several shards
482 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
483 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
484 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
485 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
489 wfProfileOut( __METHOD__
. '-' . $this->name
);
490 wfProfileOut( __METHOD__
);
495 * @see FileBackendStore::doSecure()
498 protected function doSecureInternal( $container, $dir, array $params ) {
499 return Status
::newGood();
502 final protected function doPublish( array $params ) {
503 wfProfileIn( __METHOD__
);
504 wfProfileIn( __METHOD__
. '-' . $this->name
);
505 $status = Status
::newGood();
507 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
508 if ( $dir === null ) {
509 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
510 wfProfileOut( __METHOD__
. '-' . $this->name
);
511 wfProfileOut( __METHOD__
);
512 return $status; // invalid storage path
515 if ( $shard !== null ) { // confined to a single container/shard
516 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
517 } else { // directory is on several shards
518 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
519 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
520 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
521 $status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
525 wfProfileOut( __METHOD__
. '-' . $this->name
);
526 wfProfileOut( __METHOD__
);
531 * @see FileBackendStore::doPublish()
534 protected function doPublishInternal( $container, $dir, array $params ) {
535 return Status
::newGood();
538 final protected function doClean( array $params ) {
539 wfProfileIn( __METHOD__
);
540 wfProfileIn( __METHOD__
. '-' . $this->name
);
541 $status = Status
::newGood();
543 // Recursive: first delete all empty subdirs recursively
544 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
545 $subDirsRel = $this->getTopDirectoryList( array( 'dir' => $params['dir'] ) );
546 if ( $subDirsRel !== null ) { // no errors
547 foreach ( $subDirsRel as $subDirRel ) {
548 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
549 $status->merge( $this->doClean( array( 'dir' => $subDir ) +
$params ) );
551 unset( $subDirsRel ); // free directory for rmdir() on Windows (for FS backends)
555 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
556 if ( $dir === null ) {
557 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
558 wfProfileOut( __METHOD__
. '-' . $this->name
);
559 wfProfileOut( __METHOD__
);
560 return $status; // invalid storage path
563 // Attempt to lock this directory...
564 $filesLockEx = array( $params['dir'] );
565 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
566 if ( !$status->isOK() ) {
567 wfProfileOut( __METHOD__
. '-' . $this->name
);
568 wfProfileOut( __METHOD__
);
569 return $status; // abort
572 if ( $shard !== null ) { // confined to a single container/shard
573 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
574 $this->deleteContainerCache( $fullCont ); // purge cache
575 } else { // directory is on several shards
576 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
577 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
578 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
579 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
580 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
584 wfProfileOut( __METHOD__
. '-' . $this->name
);
585 wfProfileOut( __METHOD__
);
590 * @see FileBackendStore::doClean()
593 protected function doCleanInternal( $container, $dir, array $params ) {
594 return Status
::newGood();
597 final public function fileExists( array $params ) {
598 wfProfileIn( __METHOD__
);
599 wfProfileIn( __METHOD__
. '-' . $this->name
);
600 $stat = $this->getFileStat( $params );
601 wfProfileOut( __METHOD__
. '-' . $this->name
);
602 wfProfileOut( __METHOD__
);
603 return ( $stat === null ) ?
null : (bool)$stat; // null => failure
606 final public function getFileTimestamp( array $params ) {
607 wfProfileIn( __METHOD__
);
608 wfProfileIn( __METHOD__
. '-' . $this->name
);
609 $stat = $this->getFileStat( $params );
610 wfProfileOut( __METHOD__
. '-' . $this->name
);
611 wfProfileOut( __METHOD__
);
612 return $stat ?
$stat['mtime'] : false;
615 final public function getFileSize( array $params ) {
616 wfProfileIn( __METHOD__
);
617 wfProfileIn( __METHOD__
. '-' . $this->name
);
618 $stat = $this->getFileStat( $params );
619 wfProfileOut( __METHOD__
. '-' . $this->name
);
620 wfProfileOut( __METHOD__
);
621 return $stat ?
$stat['size'] : false;
624 final public function getFileStat( array $params ) {
625 $path = self
::normalizeStoragePath( $params['src'] );
626 if ( $path === null ) {
627 return false; // invalid storage path
629 wfProfileIn( __METHOD__
);
630 wfProfileIn( __METHOD__
. '-' . $this->name
);
631 $latest = !empty( $params['latest'] ); // use latest data?
632 if ( !$this->cheapCache
->has( $path, 'stat', self
::CACHE_TTL
) ) {
633 $this->primeFileCache( array( $path ) ); // check persistent cache
635 if ( $this->cheapCache
->has( $path, 'stat', self
::CACHE_TTL
) ) {
636 $stat = $this->cheapCache
->get( $path, 'stat' );
637 // If we want the latest data, check that this cached
638 // value was in fact fetched with the latest available data.
639 if ( is_array( $stat ) ) {
640 if ( !$latest ||
$stat['latest'] ) {
641 wfProfileOut( __METHOD__
. '-' . $this->name
);
642 wfProfileOut( __METHOD__
);
645 } elseif ( in_array( $stat, array( 'NOT_EXIST', 'NOT_EXIST_LATEST' ) ) ) {
646 if ( !$latest ||
$stat === 'NOT_EXIST_LATEST' ) {
647 wfProfileOut( __METHOD__
. '-' . $this->name
);
648 wfProfileOut( __METHOD__
);
653 wfProfileIn( __METHOD__
. '-miss' );
654 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
655 $stat = $this->doGetFileStat( $params );
656 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
657 wfProfileOut( __METHOD__
. '-miss' );
658 if ( is_array( $stat ) ) { // file exists
659 $stat['latest'] = $latest;
660 $this->cheapCache
->set( $path, 'stat', $stat );
661 $this->setFileCache( $path, $stat ); // update persistent cache
662 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
663 $this->cheapCache
->set( $path, 'sha1',
664 array( 'hash' => $stat['sha1'], 'latest' => $latest ) );
666 } elseif ( $stat === false ) { // file does not exist
667 $this->cheapCache
->set( $path, 'stat', $latest ?
'NOT_EXIST_LATEST' : 'NOT_EXIST' );
668 $this->cheapCache
->set( $path, 'sha1', // the SHA-1 must be false too
669 array( 'hash' => false, 'latest' => $latest ) );
670 wfDebug( __METHOD__
. ": File $path does not exist.\n" );
671 } else { // an error occurred
672 wfDebug( __METHOD__
. ": Could not stat file $path.\n" );
674 wfProfileOut( __METHOD__
. '-' . $this->name
);
675 wfProfileOut( __METHOD__
);
680 * @see FileBackendStore::getFileStat()
682 abstract protected function doGetFileStat( array $params );
684 public function getFileContentsMulti( array $params ) {
685 wfProfileIn( __METHOD__
);
686 wfProfileIn( __METHOD__
. '-' . $this->name
);
688 $params = $this->setConcurrencyFlags( $params );
689 $contents = $this->doGetFileContentsMulti( $params );
691 wfProfileOut( __METHOD__
. '-' . $this->name
);
692 wfProfileOut( __METHOD__
);
697 * @see FileBackendStore::getFileContentsMulti()
700 protected function doGetFileContentsMulti( array $params ) {
702 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
703 wfSuppressWarnings();
704 $contents[$path] = $fsFile ?
file_get_contents( $fsFile->getPath() ) : false;
710 final public function getFileSha1Base36( array $params ) {
711 $path = self
::normalizeStoragePath( $params['src'] );
712 if ( $path === null ) {
713 return false; // invalid storage path
715 wfProfileIn( __METHOD__
);
716 wfProfileIn( __METHOD__
. '-' . $this->name
);
717 $latest = !empty( $params['latest'] ); // use latest data?
718 if ( $this->cheapCache
->has( $path, 'sha1', self
::CACHE_TTL
) ) {
719 $stat = $this->cheapCache
->get( $path, 'sha1' );
720 // If we want the latest data, check that this cached
721 // value was in fact fetched with the latest available data.
722 if ( !$latest ||
$stat['latest'] ) {
723 wfProfileOut( __METHOD__
. '-' . $this->name
);
724 wfProfileOut( __METHOD__
);
725 return $stat['hash'];
728 wfProfileIn( __METHOD__
. '-miss' );
729 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
730 $hash = $this->doGetFileSha1Base36( $params );
731 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
732 wfProfileOut( __METHOD__
. '-miss' );
733 $this->cheapCache
->set( $path, 'sha1', array( 'hash' => $hash, 'latest' => $latest ) );
734 wfProfileOut( __METHOD__
. '-' . $this->name
);
735 wfProfileOut( __METHOD__
);
740 * @see FileBackendStore::getFileSha1Base36()
741 * @return bool|string
743 protected function doGetFileSha1Base36( array $params ) {
744 $fsFile = $this->getLocalReference( $params );
748 return $fsFile->getSha1Base36();
752 final public function getFileProps( array $params ) {
753 wfProfileIn( __METHOD__
);
754 wfProfileIn( __METHOD__
. '-' . $this->name
);
755 $fsFile = $this->getLocalReference( $params );
756 $props = $fsFile ?
$fsFile->getProps() : FSFile
::placeholderProps();
757 wfProfileOut( __METHOD__
. '-' . $this->name
);
758 wfProfileOut( __METHOD__
);
762 final public function getLocalReferenceMulti( array $params ) {
763 wfProfileIn( __METHOD__
);
764 wfProfileIn( __METHOD__
. '-' . $this->name
);
766 $params = $this->setConcurrencyFlags( $params );
768 $fsFiles = array(); // (path => FSFile)
769 $latest = !empty( $params['latest'] ); // use latest data?
770 // Reuse any files already in process cache...
771 foreach ( $params['srcs'] as $src ) {
772 $path = self
::normalizeStoragePath( $src );
773 if ( $path === null ) {
774 $fsFiles[$src] = null; // invalid storage path
775 } elseif ( $this->expensiveCache
->has( $path, 'localRef' ) ) {
776 $val = $this->expensiveCache
->get( $path, 'localRef' );
777 // If we want the latest data, check that this cached
778 // value was in fact fetched with the latest available data.
779 if ( !$latest ||
$val['latest'] ) {
780 $fsFiles[$src] = $val['object'];
784 // Fetch local references of any remaning files...
785 $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
786 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
787 $fsFiles[$path] = $fsFile;
788 if ( $fsFile ) { // update the process cache...
789 $this->expensiveCache
->set( $path, 'localRef',
790 array( 'object' => $fsFile, 'latest' => $latest ) );
794 wfProfileOut( __METHOD__
. '-' . $this->name
);
795 wfProfileOut( __METHOD__
);
800 * @see FileBackendStore::getLocalReferenceMulti()
803 protected function doGetLocalReferenceMulti( array $params ) {
804 return $this->doGetLocalCopyMulti( $params );
807 final public function getLocalCopyMulti( array $params ) {
808 wfProfileIn( __METHOD__
);
809 wfProfileIn( __METHOD__
. '-' . $this->name
);
811 $params = $this->setConcurrencyFlags( $params );
812 $tmpFiles = $this->doGetLocalCopyMulti( $params );
814 wfProfileOut( __METHOD__
. '-' . $this->name
);
815 wfProfileOut( __METHOD__
);
820 * @see FileBackendStore::getLocalCopyMulti()
823 abstract protected function doGetLocalCopyMulti( array $params );
826 * @see FileBackend::getFileHttpUrl()
827 * @return string|null
829 public function getFileHttpUrl( array $params ) {
830 return null; // not supported
833 final public function streamFile( array $params ) {
834 wfProfileIn( __METHOD__
);
835 wfProfileIn( __METHOD__
. '-' . $this->name
);
836 $status = Status
::newGood();
838 $info = $this->getFileStat( $params );
839 if ( !$info ) { // let StreamFile handle the 404
840 $status->fatal( 'backend-fail-notexists', $params['src'] );
843 // Set output buffer and HTTP headers for stream
844 $extraHeaders = isset( $params['headers'] ) ?
$params['headers'] : array();
845 $res = StreamFile
::prepareForStream( $params['src'], $info, $extraHeaders );
846 if ( $res == StreamFile
::NOT_MODIFIED
) {
847 // do nothing; client cache is up to date
848 } elseif ( $res == StreamFile
::READY_STREAM
) {
849 wfProfileIn( __METHOD__
. '-send' );
850 wfProfileIn( __METHOD__
. '-send-' . $this->name
);
851 $status = $this->doStreamFile( $params );
852 wfProfileOut( __METHOD__
. '-send-' . $this->name
);
853 wfProfileOut( __METHOD__
. '-send' );
854 if ( !$status->isOK() ) {
855 // Per bug 41113, nasty things can happen if bad cache entries get
856 // stuck in cache. It's also possible that this error can come up
857 // with simple race conditions. Clear out the stat cache to be safe.
858 $this->clearCache( array( $params['src'] ) );
859 $this->deleteFileCache( $params['src'] );
860 trigger_error( "Bad stat cache or race condition for file {$params['src']}." );
863 $status->fatal( 'backend-fail-stream', $params['src'] );
866 wfProfileOut( __METHOD__
. '-' . $this->name
);
867 wfProfileOut( __METHOD__
);
872 * @see FileBackendStore::streamFile()
875 protected function doStreamFile( array $params ) {
876 $status = Status
::newGood();
878 $fsFile = $this->getLocalReference( $params );
880 $status->fatal( 'backend-fail-stream', $params['src'] );
881 } elseif ( !readfile( $fsFile->getPath() ) ) {
882 $status->fatal( 'backend-fail-stream', $params['src'] );
888 final public function directoryExists( array $params ) {
889 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
890 if ( $dir === null ) {
891 return false; // invalid storage path
893 if ( $shard !== null ) { // confined to a single container/shard
894 return $this->doDirectoryExists( $fullCont, $dir, $params );
895 } else { // directory is on several shards
896 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
897 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
898 $res = false; // response
899 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
900 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
904 } elseif ( $exists === null ) { // error?
905 $res = null; // if we don't find anything, it is indeterminate
913 * @see FileBackendStore::directoryExists()
915 * @param string $container Resolved container name
916 * @param string $dir Resolved path relative to container
917 * @param array $params
920 abstract protected function doDirectoryExists( $container, $dir, array $params );
922 final public function getDirectoryList( array $params ) {
923 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
924 if ( $dir === null ) { // invalid storage path
927 if ( $shard !== null ) {
928 // File listing is confined to a single container/shard
929 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
931 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
932 // File listing spans multiple containers/shards
933 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
934 return new FileBackendStoreShardDirIterator( $this,
935 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
940 * Do not call this function from places outside FileBackend
942 * @see FileBackendStore::getDirectoryList()
944 * @param string $container Resolved container name
945 * @param string $dir Resolved path relative to container
946 * @param array $params
947 * @return Traversable|Array|null Returns null on failure
949 abstract public function getDirectoryListInternal( $container, $dir, array $params );
951 final public function getFileList( array $params ) {
952 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
953 if ( $dir === null ) { // invalid storage path
956 if ( $shard !== null ) {
957 // File listing is confined to a single container/shard
958 return $this->getFileListInternal( $fullCont, $dir, $params );
960 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
961 // File listing spans multiple containers/shards
962 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
963 return new FileBackendStoreShardFileIterator( $this,
964 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
969 * Do not call this function from places outside FileBackend
971 * @see FileBackendStore::getFileList()
973 * @param string $container Resolved container name
974 * @param string $dir Resolved path relative to container
975 * @param array $params
976 * @return Traversable|Array|null Returns null on failure
978 abstract public function getFileListInternal( $container, $dir, array $params );
981 * Return a list of FileOp objects from a list of operations.
982 * Do not call this function from places outside FileBackend.
984 * The result must have the same number of items as the input.
985 * An exception is thrown if an unsupported operation is requested.
987 * @param array $ops Same format as doOperations()
988 * @return Array List of FileOp objects
989 * @throws MWException
991 final public function getOperationsInternal( array $ops ) {
992 $supportedOps = array(
993 'store' => 'StoreFileOp',
994 'copy' => 'CopyFileOp',
995 'move' => 'MoveFileOp',
996 'delete' => 'DeleteFileOp',
997 'create' => 'CreateFileOp',
998 'describe' => 'DescribeFileOp',
999 'null' => 'NullFileOp'
1002 $performOps = array(); // array of FileOp objects
1003 // Build up ordered array of FileOps...
1004 foreach ( $ops as $operation ) {
1005 $opName = $operation['op'];
1006 if ( isset( $supportedOps[$opName] ) ) {
1007 $class = $supportedOps[$opName];
1008 // Get params for this operation
1009 $params = $operation;
1010 // Append the FileOp class
1011 $performOps[] = new $class( $this, $params );
1013 throw new MWException( "Operation '$opName' is not supported." );
1021 * Get a list of storage paths to lock for a list of operations
1022 * Returns an array with 'sh' (shared) and 'ex' (exclusive) keys,
1023 * each corresponding to a list of storage paths to be locked.
1024 * All returned paths are normalized.
1026 * @param array $performOps List of FileOp objects
1027 * @return Array ('sh' => list of paths, 'ex' => list of paths)
1029 final public function getPathsToLockForOpsInternal( array $performOps ) {
1030 // Build up a list of files to lock...
1031 $paths = array( 'sh' => array(), 'ex' => array() );
1032 foreach ( $performOps as $fileOp ) {
1033 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1034 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1036 // Optimization: if doing an EX lock anyway, don't also set an SH one
1037 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1038 // Get a shared lock on the parent directory of each path changed
1039 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1044 public function getScopedLocksForOps( array $ops, Status
$status ) {
1045 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1047 $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status ),
1048 $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status )
1052 final protected function doOperationsInternal( array $ops, array $opts ) {
1053 wfProfileIn( __METHOD__
);
1054 wfProfileIn( __METHOD__
. '-' . $this->name
);
1055 $status = Status
::newGood();
1057 // Fix up custom header name/value pairs...
1058 $ops = array_map( array( $this, 'stripInvalidHeadersFromOp' ), $ops );
1060 // Build up a list of FileOps...
1061 $performOps = $this->getOperationsInternal( $ops );
1063 // Acquire any locks as needed...
1064 if ( empty( $opts['nonLocking'] ) ) {
1065 // Build up a list of files to lock...
1066 $paths = $this->getPathsToLockForOpsInternal( $performOps );
1067 // Try to lock those files for the scope of this function...
1068 $scopeLockS = $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status );
1069 $scopeLockE = $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status );
1070 if ( !$status->isOK() ) {
1071 wfProfileOut( __METHOD__
. '-' . $this->name
);
1072 wfProfileOut( __METHOD__
);
1073 return $status; // abort
1077 // Clear any file cache entries (after locks acquired)
1078 if ( empty( $opts['preserveCache'] ) ) {
1079 $this->clearCache();
1082 // Load from the persistent file and container caches
1083 $this->primeFileCache( $performOps );
1084 $this->primeContainerCache( $performOps );
1086 // Actually attempt the operation batch...
1087 $opts = $this->setConcurrencyFlags( $opts );
1088 $subStatus = FileOpBatch
::attempt( $performOps, $opts, $this->fileJournal
);
1090 // Merge errors into status fields
1091 $status->merge( $subStatus );
1092 $status->success
= $subStatus->success
; // not done in merge()
1094 wfProfileOut( __METHOD__
. '-' . $this->name
);
1095 wfProfileOut( __METHOD__
);
1099 final protected function doQuickOperationsInternal( array $ops ) {
1100 wfProfileIn( __METHOD__
);
1101 wfProfileIn( __METHOD__
. '-' . $this->name
);
1102 $status = Status
::newGood();
1104 // Fix up custom header name/value pairs...
1105 $ops = array_map( array( $this, 'stripInvalidHeadersFromOp' ), $ops );
1107 // Clear any file cache entries
1108 $this->clearCache();
1110 $supportedOps = array( 'create', 'store', 'copy', 'move', 'delete', 'null' );
1111 $async = ( $this->parallelize
=== 'implicit' && count( $ops ) > 1 );
1112 $maxConcurrency = $this->concurrency
; // throttle
1114 $statuses = array(); // array of (index => Status)
1115 $fileOpHandles = array(); // list of (index => handle) arrays
1116 $curFileOpHandles = array(); // current handle batch
1117 // Perform the sync-only ops and build up op handles for the async ops...
1118 foreach ( $ops as $index => $params ) {
1119 if ( !in_array( $params['op'], $supportedOps ) ) {
1120 wfProfileOut( __METHOD__
. '-' . $this->name
);
1121 wfProfileOut( __METHOD__
);
1122 throw new MWException( "Operation '{$params['op']}' is not supported." );
1124 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1125 $subStatus = $this->$method( array( 'async' => $async ) +
$params );
1126 if ( $subStatus->value
instanceof FileBackendStoreOpHandle
) { // async
1127 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1128 $fileOpHandles[] = $curFileOpHandles; // push this batch
1129 $curFileOpHandles = array();
1131 $curFileOpHandles[$index] = $subStatus->value
; // keep index
1132 } else { // error or completed
1133 $statuses[$index] = $subStatus; // keep index
1136 if ( count( $curFileOpHandles ) ) {
1137 $fileOpHandles[] = $curFileOpHandles; // last batch
1139 // Do all the async ops that can be done concurrently...
1140 foreach ( $fileOpHandles as $fileHandleBatch ) {
1141 $statuses = $statuses +
$this->executeOpHandlesInternal( $fileHandleBatch );
1143 // Marshall and merge all the responses...
1144 foreach ( $statuses as $index => $subStatus ) {
1145 $status->merge( $subStatus );
1146 if ( $subStatus->isOK() ) {
1147 $status->success
[$index] = true;
1148 ++
$status->successCount
;
1150 $status->success
[$index] = false;
1151 ++
$status->failCount
;
1155 wfProfileOut( __METHOD__
. '-' . $this->name
);
1156 wfProfileOut( __METHOD__
);
1161 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1162 * The resulting Status object fields will correspond
1163 * to the order in which the handles where given.
1165 * @param array $handles List of FileBackendStoreOpHandle objects
1166 * @return Array Map of Status objects
1167 * @throws MWException
1169 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1170 wfProfileIn( __METHOD__
);
1171 wfProfileIn( __METHOD__
. '-' . $this->name
);
1172 foreach ( $fileOpHandles as $fileOpHandle ) {
1173 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle
) ) {
1174 wfProfileOut( __METHOD__
. '-' . $this->name
);
1175 wfProfileOut( __METHOD__
);
1176 throw new MWException( "Given a non-FileBackendStoreOpHandle object." );
1177 } elseif ( $fileOpHandle->backend
->getName() !== $this->getName() ) {
1178 wfProfileOut( __METHOD__
. '-' . $this->name
);
1179 wfProfileOut( __METHOD__
);
1180 throw new MWException( "Given a FileBackendStoreOpHandle for the wrong backend." );
1183 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1184 foreach ( $fileOpHandles as $fileOpHandle ) {
1185 $fileOpHandle->closeResources();
1187 wfProfileOut( __METHOD__
. '-' . $this->name
);
1188 wfProfileOut( __METHOD__
);
1193 * @see FileBackendStore::executeOpHandlesInternal()
1194 * @param array $fileOpHandles
1195 * @throws MWException
1196 * @return Array List of corresponding Status objects
1198 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1199 foreach ( $fileOpHandles as $fileOpHandle ) { // OK if empty
1200 throw new MWException( "This backend supports no asynchronous operations." );
1206 * Strip long HTTP headers from a file operation.
1207 * Most headers are just numbers, but some are allowed to be long.
1208 * This function is useful for cleaning up headers and avoiding backend
1209 * specific errors, especially in the middle of batch file operations.
1211 * @param array $op Same format as doOperation()
1214 protected function stripInvalidHeadersFromOp( array $op ) {
1215 static $longs = array( 'Content-Disposition' );
1216 if ( isset( $op['headers'] ) ) { // op sets HTTP headers
1217 foreach ( $op['headers'] as $name => $value ) {
1218 $maxHVLen = in_array( $name, $longs ) ? INF
: 255;
1219 if ( strlen( $name ) > 255 ||
strlen( $value ) > $maxHVLen ) {
1220 trigger_error( "Header '$name: $value' is too long." );
1221 unset( $op['headers'][$name] );
1222 } elseif ( !strlen( $value ) ) {
1223 $op['headers'][$name] = ''; // null/false => ""
1230 final public function preloadCache( array $paths ) {
1231 $fullConts = array(); // full container names
1232 foreach ( $paths as $path ) {
1233 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1234 $fullConts[] = $fullCont;
1236 // Load from the persistent file and container caches
1237 $this->primeContainerCache( $fullConts );
1238 $this->primeFileCache( $paths );
1241 final public function clearCache( array $paths = null ) {
1242 if ( is_array( $paths ) ) {
1243 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1244 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1246 if ( $paths === null ) {
1247 $this->cheapCache
->clear();
1248 $this->expensiveCache
->clear();
1250 foreach ( $paths as $path ) {
1251 $this->cheapCache
->clear( $path );
1252 $this->expensiveCache
->clear( $path );
1255 $this->doClearCache( $paths );
1259 * Clears any additional stat caches for storage paths
1261 * @see FileBackend::clearCache()
1263 * @param array $paths Storage paths (optional)
1266 protected function doClearCache( array $paths = null ) {}
1269 * Is this a key/value store where directories are just virtual?
1270 * Virtual directories exists in so much as files exists that are
1271 * prefixed with the directory path followed by a forward slash.
1275 abstract protected function directoriesAreVirtual();
1278 * Check if a container name is valid.
1279 * This checks for for length and illegal characters.
1281 * @param string $container
1284 final protected static function isValidContainerName( $container ) {
1285 // This accounts for Swift and S3 restrictions while leaving room
1286 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1287 // This disallows directory separators or traversal characters.
1288 // Note that matching strings URL encode to the same string;
1289 // in Swift, the length restriction is *after* URL encoding.
1290 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1294 * Splits a storage path into an internal container name,
1295 * an internal relative file name, and a container shard suffix.
1296 * Any shard suffix is already appended to the internal container name.
1297 * This also checks that the storage path is valid and within this backend.
1299 * If the container is sharded but a suffix could not be determined,
1300 * this means that the path can only refer to a directory and can only
1301 * be scanned by looking in all the container shards.
1303 * @param string $storagePath
1304 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1306 final protected function resolveStoragePath( $storagePath ) {
1307 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1308 if ( $backend === $this->name
) { // must be for this backend
1309 $relPath = self
::normalizeContainerPath( $relPath );
1310 if ( $relPath !== null ) {
1311 // Get shard for the normalized path if this container is sharded
1312 $cShard = $this->getContainerShard( $container, $relPath );
1313 // Validate and sanitize the relative path (backend-specific)
1314 $relPath = $this->resolveContainerPath( $container, $relPath );
1315 if ( $relPath !== null ) {
1316 // Prepend any wiki ID prefix to the container name
1317 $container = $this->fullContainerName( $container );
1318 if ( self
::isValidContainerName( $container ) ) {
1319 // Validate and sanitize the container name (backend-specific)
1320 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1321 if ( $container !== null ) {
1322 return array( $container, $relPath, $cShard );
1328 return array( null, null, null );
1332 * Like resolveStoragePath() except null values are returned if
1333 * the container is sharded and the shard could not be determined
1334 * or if the path ends with '/'. The later case is illegal for FS
1335 * backends and can confuse listings for object store backends.
1337 * This function is used when resolving paths that must be valid
1338 * locations for files. Directory and listing functions should
1339 * generally just use resolveStoragePath() instead.
1341 * @see FileBackendStore::resolveStoragePath()
1343 * @param string $storagePath
1344 * @return Array (container, path) or (null, null) if invalid
1346 final protected function resolveStoragePathReal( $storagePath ) {
1347 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1348 if ( $cShard !== null && substr( $relPath, -1 ) !== '/' ) {
1349 return array( $container, $relPath );
1351 return array( null, null );
1355 * Get the container name shard suffix for a given path.
1356 * Any empty suffix means the container is not sharded.
1358 * @param string $container Container name
1359 * @param string $relPath Storage path relative to the container
1360 * @return string|null Returns null if shard could not be determined
1362 final protected function getContainerShard( $container, $relPath ) {
1363 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1364 if ( $levels == 1 ||
$levels == 2 ) {
1365 // Hash characters are either base 16 or 36
1366 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1367 // Get a regex that represents the shard portion of paths.
1368 // The concatenation of the captures gives us the shard.
1369 if ( $levels === 1 ) { // 16 or 36 shards per container
1370 $hashDirRegex = '(' . $char . ')';
1371 } else { // 256 or 1296 shards per container
1372 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1373 $hashDirRegex = $char . '/(' . $char . '{2})';
1374 } else { // short hash dir format (e.g. "a/b/c")
1375 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1378 // Allow certain directories to be above the hash dirs so as
1379 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1380 // They must be 2+ chars to avoid any hash directory ambiguity.
1382 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1383 return '.' . implode( '', array_slice( $m, 1 ) );
1385 return null; // failed to match
1387 return ''; // no sharding
1391 * Check if a storage path maps to a single shard.
1392 * Container dirs like "a", where the container shards on "x/xy",
1393 * can reside on several shards. Such paths are tricky to handle.
1395 * @param string $storagePath Storage path
1398 final public function isSingleShardPathInternal( $storagePath ) {
1399 list( , , $shard ) = $this->resolveStoragePath( $storagePath );
1400 return ( $shard !== null );
1404 * Get the sharding config for a container.
1405 * If greater than 0, then all file storage paths within
1406 * the container are required to be hashed accordingly.
1408 * @param string $container
1409 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
1411 final protected function getContainerHashLevels( $container ) {
1412 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1413 $config = $this->shardViaHashLevels
[$container];
1414 $hashLevels = (int)$config['levels'];
1415 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1416 $hashBase = (int)$config['base'];
1417 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1418 return array( $hashLevels, $hashBase, $config['repeat'] );
1422 return array( 0, 0, false ); // no sharding
1426 * Get a list of full container shard suffixes for a container
1428 * @param string $container
1431 final protected function getContainerSuffixes( $container ) {
1433 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1434 if ( $digits > 0 ) {
1435 $numShards = pow( $base, $digits );
1436 for ( $index = 0; $index < $numShards; $index++
) {
1437 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1444 * Get the full container name, including the wiki ID prefix
1446 * @param string $container
1449 final protected function fullContainerName( $container ) {
1450 if ( $this->wikiId
!= '' ) {
1451 return "{$this->wikiId}-$container";
1458 * Resolve a container name, checking if it's allowed by the backend.
1459 * This is intended for internal use, such as encoding illegal chars.
1460 * Subclasses can override this to be more restrictive.
1462 * @param string $container
1463 * @return string|null
1465 protected function resolveContainerName( $container ) {
1470 * Resolve a relative storage path, checking if it's allowed by the backend.
1471 * This is intended for internal use, such as encoding illegal chars or perhaps
1472 * getting absolute paths (e.g. FS based backends). Note that the relative path
1473 * may be the empty string (e.g. the path is simply to the container).
1475 * @param string $container Container name
1476 * @param string $relStoragePath Storage path relative to the container
1477 * @return string|null Path or null if not valid
1479 protected function resolveContainerPath( $container, $relStoragePath ) {
1480 return $relStoragePath;
1484 * Get the cache key for a container
1486 * @param string $container Resolved container name
1489 private function containerCacheKey( $container ) {
1490 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1494 * Set the cached info for a container
1496 * @param string $container Resolved container name
1497 * @param array $val Information to cache
1500 final protected function setContainerCache( $container, array $val ) {
1501 $this->memCache
->add( $this->containerCacheKey( $container ), $val, 14 * 86400 );
1505 * Delete the cached info for a container.
1506 * The cache key is salted for a while to prevent race conditions.
1508 * @param string $container Resolved container name
1511 final protected function deleteContainerCache( $container ) {
1512 if ( !$this->memCache
->set( $this->containerCacheKey( $container ), 'PURGED', 300 ) ) {
1513 trigger_error( "Unable to delete stat cache for container $container." );
1518 * Do a batch lookup from cache for container stats for all containers
1519 * used in a list of container names, storage paths, or FileOp objects.
1520 * This loads the persistent cache values into the process cache.
1522 * @param Array $items
1525 final protected function primeContainerCache( array $items ) {
1526 wfProfileIn( __METHOD__
);
1527 wfProfileIn( __METHOD__
. '-' . $this->name
);
1529 $paths = array(); // list of storage paths
1530 $contNames = array(); // (cache key => resolved container name)
1531 // Get all the paths/containers from the items...
1532 foreach ( $items as $item ) {
1533 if ( $item instanceof FileOp
) {
1534 $paths = array_merge( $paths, $item->storagePathsRead() );
1535 $paths = array_merge( $paths, $item->storagePathsChanged() );
1536 } elseif ( self
::isStoragePath( $item ) ) {
1538 } elseif ( is_string( $item ) ) { // full container name
1539 $contNames[$this->containerCacheKey( $item )] = $item;
1542 // Get all the corresponding cache keys for paths...
1543 foreach ( $paths as $path ) {
1544 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1545 if ( $fullCont !== null ) { // valid path for this backend
1546 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1550 $contInfo = array(); // (resolved container name => cache value)
1551 // Get all cache entries for these container cache keys...
1552 $values = $this->memCache
->getMulti( array_keys( $contNames ) );
1553 foreach ( $values as $cacheKey => $val ) {
1554 $contInfo[$contNames[$cacheKey]] = $val;
1557 // Populate the container process cache for the backend...
1558 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1560 wfProfileOut( __METHOD__
. '-' . $this->name
);
1561 wfProfileOut( __METHOD__
);
1565 * Fill the backend-specific process cache given an array of
1566 * resolved container names and their corresponding cached info.
1567 * Only containers that actually exist should appear in the map.
1569 * @param array $containerInfo Map of resolved container names to cached info
1572 protected function doPrimeContainerCache( array $containerInfo ) {}
1575 * Get the cache key for a file path
1577 * @param string $path Normalized storage path
1580 private function fileCacheKey( $path ) {
1581 return wfMemcKey( 'backend', $this->getName(), 'file', sha1( $path ) );
1585 * Set the cached stat info for a file path.
1586 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1587 * salting for the case when a file is created at a path were there was none before.
1589 * @param string $path Storage path
1590 * @param array $val Stat information to cache
1593 final protected function setFileCache( $path, array $val ) {
1594 $path = FileBackend
::normalizeStoragePath( $path );
1595 if ( $path === null ) {
1596 return; // invalid storage path
1598 $age = time() - wfTimestamp( TS_UNIX
, $val['mtime'] );
1599 $ttl = min( 7 * 86400, max( 300, floor( .1 * $age ) ) );
1600 $this->memCache
->add( $this->fileCacheKey( $path ), $val, $ttl );
1604 * Delete the cached stat info for a file path.
1605 * The cache key is salted for a while to prevent race conditions.
1606 * Since negatives (404s) are not cached, this does not need to be called when
1607 * a file is created at a path were there was none before.
1609 * @param string $path Storage path
1612 final protected function deleteFileCache( $path ) {
1613 $path = FileBackend
::normalizeStoragePath( $path );
1614 if ( $path === null ) {
1615 return; // invalid storage path
1617 if ( !$this->memCache
->set( $this->fileCacheKey( $path ), 'PURGED', 300 ) ) {
1618 trigger_error( "Unable to delete stat cache for file $path." );
1623 * Do a batch lookup from cache for file stats for all paths
1624 * used in a list of storage paths or FileOp objects.
1625 * This loads the persistent cache values into the process cache.
1627 * @param array $items List of storage paths or FileOps
1630 final protected function primeFileCache( array $items ) {
1631 wfProfileIn( __METHOD__
);
1632 wfProfileIn( __METHOD__
. '-' . $this->name
);
1634 $paths = array(); // list of storage paths
1635 $pathNames = array(); // (cache key => storage path)
1636 // Get all the paths/containers from the items...
1637 foreach ( $items as $item ) {
1638 if ( $item instanceof FileOp
) {
1639 $paths = array_merge( $paths, $item->storagePathsRead() );
1640 $paths = array_merge( $paths, $item->storagePathsChanged() );
1641 } elseif ( self
::isStoragePath( $item ) ) {
1642 $paths[] = FileBackend
::normalizeStoragePath( $item );
1645 // Get rid of any paths that failed normalization...
1646 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1647 // Get all the corresponding cache keys for paths...
1648 foreach ( $paths as $path ) {
1649 list( , $rel, ) = $this->resolveStoragePath( $path );
1650 if ( $rel !== null ) { // valid path for this backend
1651 $pathNames[$this->fileCacheKey( $path )] = $path;
1654 // Get all cache entries for these container cache keys...
1655 $values = $this->memCache
->getMulti( array_keys( $pathNames ) );
1656 foreach ( $values as $cacheKey => $val ) {
1657 if ( is_array( $val ) ) {
1658 $path = $pathNames[$cacheKey];
1659 $this->cheapCache
->set( $path, 'stat', $val );
1660 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1661 $this->cheapCache
->set( $path, 'sha1',
1662 array( 'hash' => $val['sha1'], 'latest' => $val['latest'] ) );
1667 wfProfileOut( __METHOD__
. '-' . $this->name
);
1668 wfProfileOut( __METHOD__
);
1672 * Set the 'concurrency' option from a list of operation options
1674 * @param array $opts Map of operation options
1677 final protected function setConcurrencyFlags( array $opts ) {
1678 $opts['concurrency'] = 1; // off
1679 if ( $this->parallelize
=== 'implicit' ) {
1680 if ( !isset( $opts['parallelize'] ) ||
$opts['parallelize'] ) {
1681 $opts['concurrency'] = $this->concurrency
;
1683 } elseif ( $this->parallelize
=== 'explicit' ) {
1684 if ( !empty( $opts['parallelize'] ) ) {
1685 $opts['concurrency'] = $this->concurrency
;
1693 * FileBackendStore helper class for performing asynchronous file operations.
1695 * For example, calling FileBackendStore::createInternal() with the "async"
1696 * param flag may result in a Status that contains this object as a value.
1697 * This class is largely backend-specific and is mostly just "magic" to be
1698 * passed to FileBackendStore::executeOpHandlesInternal().
1700 abstract class FileBackendStoreOpHandle
{
1702 public $params = array(); // params to caller functions
1703 /** @var FileBackendStore */
1706 public $resourcesToClose = array();
1708 public $call; // string; name that identifies the function called
1711 * Close all open file handles
1715 public function closeResources() {
1716 array_map( 'fclose', $this->resourcesToClose
);
1721 * FileBackendStore helper function to handle listings that span container shards.
1722 * Do not use this class from places outside of FileBackendStore.
1724 * @ingroup FileBackend
1726 abstract class FileBackendStoreShardListIterator
extends FilterIterator
{
1727 /** @var FileBackendStore */
1732 protected $container; // string; full container name
1733 protected $directory; // string; resolved relative path
1736 protected $multiShardPaths = array(); // (rel path => 1)
1739 * @param FileBackendStore $backend
1740 * @param string $container Full storage container name
1741 * @param string $dir Storage directory relative to container
1742 * @param array $suffixes List of container shard suffixes
1743 * @param array $params
1745 public function __construct(
1746 FileBackendStore
$backend, $container, $dir, array $suffixes, array $params
1748 $this->backend
= $backend;
1749 $this->container
= $container;
1750 $this->directory
= $dir;
1751 $this->params
= $params;
1753 $iter = new AppendIterator();
1754 foreach ( $suffixes as $suffix ) {
1755 $iter->append( $this->listFromShard( $this->container
. $suffix ) );
1758 parent
::__construct( $iter );
1761 public function accept() {
1762 $rel = $this->getInnerIterator()->current(); // path relative to given directory
1763 $path = $this->params
['dir'] . "/{$rel}"; // full storage path
1764 if ( $this->backend
->isSingleShardPathInternal( $path ) ) {
1765 return true; // path is only on one shard; no issue with duplicates
1766 } elseif ( isset( $this->multiShardPaths
[$rel] ) ) {
1767 // Don't keep listing paths that are on multiple shards
1770 $this->multiShardPaths
[$rel] = 1;
1775 public function rewind() {
1777 $this->multiShardPaths
= array();
1781 * Get the list for a given container shard
1783 * @param string $container Resolved container name
1786 abstract protected function listFromShard( $container );
1790 * Iterator for listing directories
1792 class FileBackendStoreShardDirIterator
extends FileBackendStoreShardListIterator
{
1793 protected function listFromShard( $container ) {
1794 $list = $this->backend
->getDirectoryListInternal(
1795 $container, $this->directory
, $this->params
);
1796 if ( $list === null ) {
1797 return new ArrayIterator( array() );
1799 return is_array( $list ) ?
new ArrayIterator( $list ) : $list;
1805 * Iterator for listing regular files
1807 class FileBackendStoreShardFileIterator
extends FileBackendStoreShardListIterator
{
1808 protected function listFromShard( $container ) {
1809 $list = $this->backend
->getFileListInternal(
1810 $container, $this->directory
, $this->params
);
1811 if ( $list === null ) {
1812 return new ArrayIterator( array() );
1814 return is_array( $list ) ?
new ArrayIterator( $list ) : $list;