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 * - headers : HTTP header name/value map
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.
99 * - dstExists : Whether a file exists at the destination (optimization).
100 * Callers can use "false" if no existing file is being changed.
102 * @param array $params
105 final public function createInternal( array $params ) {
106 wfProfileIn( __METHOD__
);
107 wfProfileIn( __METHOD__
. '-' . $this->name
);
108 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
109 $status = Status
::newFatal( 'backend-fail-maxsize',
110 $params['dst'], $this->maxFileSizeInternal() );
112 $status = $this->doCreateInternal( $params );
113 $this->clearCache( array( $params['dst'] ) );
114 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
115 $this->deleteFileCache( $params['dst'] ); // persistent cache
118 wfProfileOut( __METHOD__
. '-' . $this->name
);
119 wfProfileOut( __METHOD__
);
124 * @see FileBackendStore::createInternal()
127 abstract protected function doCreateInternal( array $params );
130 * Store a file into the backend from a file on disk.
131 * This will overwrite any file that exists at the destination.
132 * Do not call this function from places outside FileBackend and FileOp.
135 * - src : source path on disk
136 * - dst : destination storage path
137 * - headers : HTTP header name/value map
138 * - async : Status will be returned immediately if supported.
139 * If the status is OK, then its value field will be
140 * set to a FileBackendStoreOpHandle object.
141 * - dstExists : Whether a file exists at the destination (optimization).
142 * Callers can use "false" if no existing file is being changed.
144 * @param array $params
147 final public function storeInternal( array $params ) {
148 wfProfileIn( __METHOD__
);
149 wfProfileIn( __METHOD__
. '-' . $this->name
);
150 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
151 $status = Status
::newFatal( 'backend-fail-maxsize',
152 $params['dst'], $this->maxFileSizeInternal() );
154 $status = $this->doStoreInternal( $params );
155 $this->clearCache( array( $params['dst'] ) );
156 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
157 $this->deleteFileCache( $params['dst'] ); // persistent cache
160 wfProfileOut( __METHOD__
. '-' . $this->name
);
161 wfProfileOut( __METHOD__
);
166 * @see FileBackendStore::storeInternal()
169 abstract protected function doStoreInternal( array $params );
172 * Copy a file from one storage path to another in the backend.
173 * This will overwrite any file that exists at the destination.
174 * Do not call this function from places outside FileBackend and FileOp.
177 * - src : source storage path
178 * - dst : destination storage path
179 * - ignoreMissingSource : do nothing if the source file does not exist
180 * - headers : HTTP header name/value map
181 * - async : Status will be returned immediately if supported.
182 * If the status is OK, then its value field will be
183 * set to a FileBackendStoreOpHandle object.
184 * - dstExists : Whether a file exists at the destination (optimization).
185 * Callers can use "false" if no existing file is being changed.
187 * @param array $params
190 final public function copyInternal( array $params ) {
191 wfProfileIn( __METHOD__
);
192 wfProfileIn( __METHOD__
. '-' . $this->name
);
193 $status = $this->doCopyInternal( $params );
194 $this->clearCache( array( $params['dst'] ) );
195 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
196 $this->deleteFileCache( $params['dst'] ); // persistent cache
198 wfProfileOut( __METHOD__
. '-' . $this->name
);
199 wfProfileOut( __METHOD__
);
204 * @see FileBackendStore::copyInternal()
207 abstract protected function doCopyInternal( array $params );
210 * Delete a file at the storage path.
211 * Do not call this function from places outside FileBackend and FileOp.
214 * - src : source storage path
215 * - ignoreMissingSource : do nothing if the source file does not exist
216 * - async : Status will be returned immediately if supported.
217 * If the status is OK, then its value field will be
218 * set to a FileBackendStoreOpHandle object.
220 * @param array $params
223 final public function deleteInternal( array $params ) {
224 wfProfileIn( __METHOD__
);
225 wfProfileIn( __METHOD__
. '-' . $this->name
);
226 $status = $this->doDeleteInternal( $params );
227 $this->clearCache( array( $params['src'] ) );
228 $this->deleteFileCache( $params['src'] ); // persistent cache
229 wfProfileOut( __METHOD__
. '-' . $this->name
);
230 wfProfileOut( __METHOD__
);
235 * @see FileBackendStore::deleteInternal()
238 abstract protected function doDeleteInternal( array $params );
241 * Move a file from one storage path to another in the backend.
242 * This will overwrite any file that exists at the destination.
243 * Do not call this function from places outside FileBackend and FileOp.
246 * - src : source storage path
247 * - dst : destination storage path
248 * - ignoreMissingSource : do nothing if the source file does not exist
249 * - headers : HTTP header name/value map
250 * - async : Status will be returned immediately if supported.
251 * If the status is OK, then its value field will be
252 * set to a FileBackendStoreOpHandle object.
253 * - dstExists : Whether a file exists at the destination (optimization).
254 * Callers can use "false" if no existing file is being changed.
256 * @param array $params
259 final public function moveInternal( array $params ) {
260 wfProfileIn( __METHOD__
);
261 wfProfileIn( __METHOD__
. '-' . $this->name
);
262 $status = $this->doMoveInternal( $params );
263 $this->clearCache( array( $params['src'], $params['dst'] ) );
264 $this->deleteFileCache( $params['src'] ); // persistent cache
265 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
266 $this->deleteFileCache( $params['dst'] ); // persistent cache
268 wfProfileOut( __METHOD__
. '-' . $this->name
);
269 wfProfileOut( __METHOD__
);
274 * @see FileBackendStore::moveInternal()
277 protected function doMoveInternal( array $params ) {
278 unset( $params['async'] ); // two steps, won't work here :)
279 $nsrc = FileBackend
::normalizeStoragePath( $params['src'] );
280 $ndst = FileBackend
::normalizeStoragePath( $params['dst'] );
281 // Copy source to dest
282 $status = $this->copyInternal( $params );
283 if ( $nsrc !== $ndst && $status->isOK() ) {
284 // Delete source (only fails due to races or network problems)
285 $status->merge( $this->deleteInternal( array( 'src' => $params['src'] ) ) );
286 $status->setResult( true, $status->value
); // ignore delete() errors
292 * Alter metadata for a file at the storage path.
293 * Do not call this function from places outside FileBackend and FileOp.
296 * - src : source storage path
297 * - headers : HTTP header name/value map
298 * - async : Status will be returned immediately if supported.
299 * If the status is OK, then its value field will be
300 * set to a FileBackendStoreOpHandle object.
302 * @param array $params
305 final public function describeInternal( array $params ) {
306 wfProfileIn( __METHOD__
);
307 wfProfileIn( __METHOD__
. '-' . $this->name
);
308 if ( count( $params['headers'] ) ) {
309 $status = $this->doDescribeInternal( $params );
310 $this->clearCache( array( $params['src'] ) );
311 $this->deleteFileCache( $params['src'] ); // persistent cache
313 $status = Status
::newGood(); // nothing to do
315 wfProfileOut( __METHOD__
. '-' . $this->name
);
316 wfProfileOut( __METHOD__
);
321 * @see FileBackendStore::describeInternal()
324 protected function doDescribeInternal( array $params ) {
325 return Status
::newGood();
329 * No-op file operation that does nothing.
330 * Do not call this function from places outside FileBackend and FileOp.
332 * @param array $params
335 final public function nullInternal( array $params ) {
336 return Status
::newGood();
340 * @see FileBackend::concatenate()
343 final public function concatenate( array $params ) {
344 wfProfileIn( __METHOD__
);
345 wfProfileIn( __METHOD__
. '-' . $this->name
);
346 $status = Status
::newGood();
348 // Try to lock the source files for the scope of this function
349 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager
::LOCK_UW
, $status );
350 if ( $status->isOK() ) {
351 // Actually do the file concatenation...
352 $start_time = microtime( true );
353 $status->merge( $this->doConcatenate( $params ) );
354 $sec = microtime( true ) - $start_time;
355 if ( !$status->isOK() ) {
356 wfDebugLog( 'FileOperation', get_class( $this ) . " failed to concatenate " .
357 count( $params['srcs'] ) . " file(s) [$sec sec]" );
361 wfProfileOut( __METHOD__
. '-' . $this->name
);
362 wfProfileOut( __METHOD__
);
367 * @see FileBackendStore::concatenate()
370 protected function doConcatenate( array $params ) {
371 $status = Status
::newGood();
372 $tmpPath = $params['dst']; // convenience
373 unset( $params['latest'] ); // sanity
375 // Check that the specified temp file is valid...
376 wfSuppressWarnings();
377 $ok = ( is_file( $tmpPath ) && filesize( $tmpPath ) == 0 );
379 if ( !$ok ) { // not present or not empty
380 $status->fatal( 'backend-fail-opentemp', $tmpPath );
384 // Get local FS versions of the chunks needed for the concatenation...
385 $fsFiles = $this->getLocalReferenceMulti( $params );
386 foreach ( $fsFiles as $path => &$fsFile ) {
387 if ( !$fsFile ) { // chunk failed to download?
388 $fsFile = $this->getLocalReference( array( 'src' => $path ) );
389 if ( !$fsFile ) { // retry failed?
390 $status->fatal( 'backend-fail-read', $path );
395 unset( $fsFile ); // unset reference so we can reuse $fsFile
397 // Get a handle for the destination temp file
398 $tmpHandle = fopen( $tmpPath, 'ab' );
399 if ( $tmpHandle === false ) {
400 $status->fatal( 'backend-fail-opentemp', $tmpPath );
404 // Build up the temp file using the source chunks (in order)...
405 foreach ( $fsFiles as $virtualSource => $fsFile ) {
406 // Get a handle to the local FS version
407 $sourceHandle = fopen( $fsFile->getPath(), 'rb' );
408 if ( $sourceHandle === false ) {
409 fclose( $tmpHandle );
410 $status->fatal( 'backend-fail-read', $virtualSource );
413 // Append chunk to file (pass chunk size to avoid magic quotes)
414 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
415 fclose( $sourceHandle );
416 fclose( $tmpHandle );
417 $status->fatal( 'backend-fail-writetemp', $tmpPath );
420 fclose( $sourceHandle );
422 if ( !fclose( $tmpHandle ) ) {
423 $status->fatal( 'backend-fail-closetemp', $tmpPath );
427 clearstatcache(); // temp file changed
433 * @see FileBackend::doPrepare()
436 final protected function doPrepare( array $params ) {
437 wfProfileIn( __METHOD__
);
438 wfProfileIn( __METHOD__
. '-' . $this->name
);
440 $status = Status
::newGood();
441 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
442 if ( $dir === null ) {
443 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
444 wfProfileOut( __METHOD__
. '-' . $this->name
);
445 wfProfileOut( __METHOD__
);
446 return $status; // invalid storage path
449 if ( $shard !== null ) { // confined to a single container/shard
450 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
451 } else { // directory is on several shards
452 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
453 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
454 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
455 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
459 wfProfileOut( __METHOD__
. '-' . $this->name
);
460 wfProfileOut( __METHOD__
);
465 * @see FileBackendStore::doPrepare()
468 protected function doPrepareInternal( $container, $dir, array $params ) {
469 return Status
::newGood();
473 * @see FileBackend::doSecure()
476 final protected function doSecure( array $params ) {
477 wfProfileIn( __METHOD__
);
478 wfProfileIn( __METHOD__
. '-' . $this->name
);
479 $status = Status
::newGood();
481 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
482 if ( $dir === null ) {
483 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
484 wfProfileOut( __METHOD__
. '-' . $this->name
);
485 wfProfileOut( __METHOD__
);
486 return $status; // invalid storage path
489 if ( $shard !== null ) { // confined to a single container/shard
490 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
491 } else { // directory is on several shards
492 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
493 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
494 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
495 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
499 wfProfileOut( __METHOD__
. '-' . $this->name
);
500 wfProfileOut( __METHOD__
);
505 * @see FileBackendStore::doSecure()
508 protected function doSecureInternal( $container, $dir, array $params ) {
509 return Status
::newGood();
513 * @see FileBackend::doPublish()
516 final protected function doPublish( array $params ) {
517 wfProfileIn( __METHOD__
);
518 wfProfileIn( __METHOD__
. '-' . $this->name
);
519 $status = Status
::newGood();
521 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
522 if ( $dir === null ) {
523 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
524 wfProfileOut( __METHOD__
. '-' . $this->name
);
525 wfProfileOut( __METHOD__
);
526 return $status; // invalid storage path
529 if ( $shard !== null ) { // confined to a single container/shard
530 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
531 } else { // directory is on several shards
532 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
533 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
534 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
535 $status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
539 wfProfileOut( __METHOD__
. '-' . $this->name
);
540 wfProfileOut( __METHOD__
);
545 * @see FileBackendStore::doPublish()
548 protected function doPublishInternal( $container, $dir, array $params ) {
549 return Status
::newGood();
553 * @see FileBackend::doClean()
556 final protected function doClean( array $params ) {
557 wfProfileIn( __METHOD__
);
558 wfProfileIn( __METHOD__
. '-' . $this->name
);
559 $status = Status
::newGood();
561 // Recursive: first delete all empty subdirs recursively
562 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
563 $subDirsRel = $this->getTopDirectoryList( array( 'dir' => $params['dir'] ) );
564 if ( $subDirsRel !== null ) { // no errors
565 foreach ( $subDirsRel as $subDirRel ) {
566 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
567 $status->merge( $this->doClean( array( 'dir' => $subDir ) +
$params ) );
569 unset( $subDirsRel ); // free directory for rmdir() on Windows (for FS backends)
573 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
574 if ( $dir === null ) {
575 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
576 wfProfileOut( __METHOD__
. '-' . $this->name
);
577 wfProfileOut( __METHOD__
);
578 return $status; // invalid storage path
581 // Attempt to lock this directory...
582 $filesLockEx = array( $params['dir'] );
583 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
584 if ( !$status->isOK() ) {
585 wfProfileOut( __METHOD__
. '-' . $this->name
);
586 wfProfileOut( __METHOD__
);
587 return $status; // abort
590 if ( $shard !== null ) { // confined to a single container/shard
591 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
592 $this->deleteContainerCache( $fullCont ); // purge cache
593 } else { // directory is on several shards
594 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
595 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
596 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
597 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
598 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
602 wfProfileOut( __METHOD__
. '-' . $this->name
);
603 wfProfileOut( __METHOD__
);
608 * @see FileBackendStore::doClean()
611 protected function doCleanInternal( $container, $dir, array $params ) {
612 return Status
::newGood();
616 * @see FileBackend::fileExists()
619 final public function fileExists( array $params ) {
620 wfProfileIn( __METHOD__
);
621 wfProfileIn( __METHOD__
. '-' . $this->name
);
622 $stat = $this->getFileStat( $params );
623 wfProfileOut( __METHOD__
. '-' . $this->name
);
624 wfProfileOut( __METHOD__
);
625 return ( $stat === null ) ?
null : (bool)$stat; // null => failure
629 * @see FileBackend::getFileTimestamp()
632 final public function getFileTimestamp( array $params ) {
633 wfProfileIn( __METHOD__
);
634 wfProfileIn( __METHOD__
. '-' . $this->name
);
635 $stat = $this->getFileStat( $params );
636 wfProfileOut( __METHOD__
. '-' . $this->name
);
637 wfProfileOut( __METHOD__
);
638 return $stat ?
$stat['mtime'] : false;
642 * @see FileBackend::getFileSize()
645 final public function getFileSize( array $params ) {
646 wfProfileIn( __METHOD__
);
647 wfProfileIn( __METHOD__
. '-' . $this->name
);
648 $stat = $this->getFileStat( $params );
649 wfProfileOut( __METHOD__
. '-' . $this->name
);
650 wfProfileOut( __METHOD__
);
651 return $stat ?
$stat['size'] : false;
655 * @see FileBackend::getFileStat()
658 final public function getFileStat( array $params ) {
659 $path = self
::normalizeStoragePath( $params['src'] );
660 if ( $path === null ) {
661 return false; // invalid storage path
663 wfProfileIn( __METHOD__
);
664 wfProfileIn( __METHOD__
. '-' . $this->name
);
665 $latest = !empty( $params['latest'] ); // use latest data?
666 if ( !$this->cheapCache
->has( $path, 'stat', self
::CACHE_TTL
) ) {
667 $this->primeFileCache( array( $path ) ); // check persistent cache
669 if ( $this->cheapCache
->has( $path, 'stat', self
::CACHE_TTL
) ) {
670 $stat = $this->cheapCache
->get( $path, 'stat' );
671 // If we want the latest data, check that this cached
672 // value was in fact fetched with the latest available data.
673 if ( is_array( $stat ) ) {
674 if ( !$latest ||
$stat['latest'] ) {
675 wfProfileOut( __METHOD__
. '-' . $this->name
);
676 wfProfileOut( __METHOD__
);
679 } elseif ( in_array( $stat, array( 'NOT_EXIST', 'NOT_EXIST_LATEST' ) ) ) {
680 if ( !$latest ||
$stat === 'NOT_EXIST_LATEST' ) {
681 wfProfileOut( __METHOD__
. '-' . $this->name
);
682 wfProfileOut( __METHOD__
);
687 wfProfileIn( __METHOD__
. '-miss' );
688 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
689 $stat = $this->doGetFileStat( $params );
690 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
691 wfProfileOut( __METHOD__
. '-miss' );
692 if ( is_array( $stat ) ) { // file exists
693 $stat['latest'] = $latest;
694 $this->cheapCache
->set( $path, 'stat', $stat );
695 $this->setFileCache( $path, $stat ); // update persistent cache
696 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
697 $this->cheapCache
->set( $path, 'sha1',
698 array( 'hash' => $stat['sha1'], 'latest' => $latest ) );
700 } elseif ( $stat === false ) { // file does not exist
701 $this->cheapCache
->set( $path, 'stat', $latest ?
'NOT_EXIST_LATEST' : 'NOT_EXIST' );
702 $this->cheapCache
->set( $path, 'sha1', // the SHA-1 must be false too
703 array( 'hash' => false, 'latest' => $latest ) );
704 wfDebug( __METHOD__
. ": File $path does not exist.\n" );
705 } else { // an error occurred
706 wfDebug( __METHOD__
. ": Could not stat file $path.\n" );
708 wfProfileOut( __METHOD__
. '-' . $this->name
);
709 wfProfileOut( __METHOD__
);
714 * @see FileBackendStore::getFileStat()
716 abstract protected function doGetFileStat( array $params );
719 * @see FileBackend::getFileContentsMulti()
722 public function getFileContentsMulti( array $params ) {
723 wfProfileIn( __METHOD__
);
724 wfProfileIn( __METHOD__
. '-' . $this->name
);
726 $params = $this->setConcurrencyFlags( $params );
727 $contents = $this->doGetFileContentsMulti( $params );
729 wfProfileOut( __METHOD__
. '-' . $this->name
);
730 wfProfileOut( __METHOD__
);
735 * @see FileBackendStore::getFileContentsMulti()
738 protected function doGetFileContentsMulti( array $params ) {
740 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
741 wfSuppressWarnings();
742 $contents[$path] = $fsFile ?
file_get_contents( $fsFile->getPath() ) : false;
749 * @see FileBackend::getFileSha1Base36()
750 * @return bool|string
752 final public function getFileSha1Base36( array $params ) {
753 $path = self
::normalizeStoragePath( $params['src'] );
754 if ( $path === null ) {
755 return false; // invalid storage path
757 wfProfileIn( __METHOD__
);
758 wfProfileIn( __METHOD__
. '-' . $this->name
);
759 $latest = !empty( $params['latest'] ); // use latest data?
760 if ( $this->cheapCache
->has( $path, 'sha1', self
::CACHE_TTL
) ) {
761 $stat = $this->cheapCache
->get( $path, 'sha1' );
762 // If we want the latest data, check that this cached
763 // value was in fact fetched with the latest available data.
764 if ( !$latest ||
$stat['latest'] ) {
765 wfProfileOut( __METHOD__
. '-' . $this->name
);
766 wfProfileOut( __METHOD__
);
767 return $stat['hash'];
770 wfProfileIn( __METHOD__
. '-miss' );
771 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
772 $hash = $this->doGetFileSha1Base36( $params );
773 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
774 wfProfileOut( __METHOD__
. '-miss' );
775 $this->cheapCache
->set( $path, 'sha1', array( 'hash' => $hash, 'latest' => $latest ) );
776 wfProfileOut( __METHOD__
. '-' . $this->name
);
777 wfProfileOut( __METHOD__
);
782 * @see FileBackendStore::getFileSha1Base36()
783 * @return bool|string
785 protected function doGetFileSha1Base36( array $params ) {
786 $fsFile = $this->getLocalReference( $params );
790 return $fsFile->getSha1Base36();
795 * @see FileBackend::getFileProps()
798 final public function getFileProps( array $params ) {
799 wfProfileIn( __METHOD__
);
800 wfProfileIn( __METHOD__
. '-' . $this->name
);
801 $fsFile = $this->getLocalReference( $params );
802 $props = $fsFile ?
$fsFile->getProps() : FSFile
::placeholderProps();
803 wfProfileOut( __METHOD__
. '-' . $this->name
);
804 wfProfileOut( __METHOD__
);
809 * @see FileBackend::getLocalReferenceMulti()
812 final public function getLocalReferenceMulti( array $params ) {
813 wfProfileIn( __METHOD__
);
814 wfProfileIn( __METHOD__
. '-' . $this->name
);
816 $params = $this->setConcurrencyFlags( $params );
818 $fsFiles = array(); // (path => FSFile)
819 $latest = !empty( $params['latest'] ); // use latest data?
820 // Reuse any files already in process cache...
821 foreach ( $params['srcs'] as $src ) {
822 $path = self
::normalizeStoragePath( $src );
823 if ( $path === null ) {
824 $fsFiles[$src] = null; // invalid storage path
825 } elseif ( $this->expensiveCache
->has( $path, 'localRef' ) ) {
826 $val = $this->expensiveCache
->get( $path, 'localRef' );
827 // If we want the latest data, check that this cached
828 // value was in fact fetched with the latest available data.
829 if ( !$latest ||
$val['latest'] ) {
830 $fsFiles[$src] = $val['object'];
834 // Fetch local references of any remaning files...
835 $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
836 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
837 $fsFiles[$path] = $fsFile;
838 if ( $fsFile ) { // update the process cache...
839 $this->expensiveCache
->set( $path, 'localRef',
840 array( 'object' => $fsFile, 'latest' => $latest ) );
844 wfProfileOut( __METHOD__
. '-' . $this->name
);
845 wfProfileOut( __METHOD__
);
850 * @see FileBackendStore::getLocalReferenceMulti()
853 protected function doGetLocalReferenceMulti( array $params ) {
854 return $this->doGetLocalCopyMulti( $params );
858 * @see FileBackend::getLocalCopyMulti()
861 final public function getLocalCopyMulti( array $params ) {
862 wfProfileIn( __METHOD__
);
863 wfProfileIn( __METHOD__
. '-' . $this->name
);
865 $params = $this->setConcurrencyFlags( $params );
866 $tmpFiles = $this->doGetLocalCopyMulti( $params );
868 wfProfileOut( __METHOD__
. '-' . $this->name
);
869 wfProfileOut( __METHOD__
);
874 * @see FileBackendStore::getLocalCopyMulti()
877 abstract protected function doGetLocalCopyMulti( array $params );
880 * @see FileBackend::getFileHttpUrl()
881 * @return string|null
883 public function getFileHttpUrl( array $params ) {
884 return null; // not supported
888 * @see FileBackend::streamFile()
891 final public function streamFile( array $params ) {
892 wfProfileIn( __METHOD__
);
893 wfProfileIn( __METHOD__
. '-' . $this->name
);
894 $status = Status
::newGood();
896 $info = $this->getFileStat( $params );
897 if ( !$info ) { // let StreamFile handle the 404
898 $status->fatal( 'backend-fail-notexists', $params['src'] );
901 // Set output buffer and HTTP headers for stream
902 $extraHeaders = isset( $params['headers'] ) ?
$params['headers'] : array();
903 $res = StreamFile
::prepareForStream( $params['src'], $info, $extraHeaders );
904 if ( $res == StreamFile
::NOT_MODIFIED
) {
905 // do nothing; client cache is up to date
906 } elseif ( $res == StreamFile
::READY_STREAM
) {
907 wfProfileIn( __METHOD__
. '-send' );
908 wfProfileIn( __METHOD__
. '-send-' . $this->name
);
909 $status = $this->doStreamFile( $params );
910 wfProfileOut( __METHOD__
. '-send-' . $this->name
);
911 wfProfileOut( __METHOD__
. '-send' );
912 if ( !$status->isOK() ) {
913 // Per bug 41113, nasty things can happen if bad cache entries get
914 // stuck in cache. It's also possible that this error can come up
915 // with simple race conditions. Clear out the stat cache to be safe.
916 $this->clearCache( array( $params['src'] ) );
917 $this->deleteFileCache( $params['src'] );
918 trigger_error( "Bad stat cache or race condition for file {$params['src']}." );
921 $status->fatal( 'backend-fail-stream', $params['src'] );
924 wfProfileOut( __METHOD__
. '-' . $this->name
);
925 wfProfileOut( __METHOD__
);
930 * @see FileBackendStore::streamFile()
933 protected function doStreamFile( array $params ) {
934 $status = Status
::newGood();
936 $fsFile = $this->getLocalReference( $params );
938 $status->fatal( 'backend-fail-stream', $params['src'] );
939 } elseif ( !readfile( $fsFile->getPath() ) ) {
940 $status->fatal( 'backend-fail-stream', $params['src'] );
947 * @see FileBackend::directoryExists()
950 final public function directoryExists( array $params ) {
951 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
952 if ( $dir === null ) {
953 return false; // invalid storage path
955 if ( $shard !== null ) { // confined to a single container/shard
956 return $this->doDirectoryExists( $fullCont, $dir, $params );
957 } else { // directory is on several shards
958 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
959 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
960 $res = false; // response
961 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
962 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
966 } elseif ( $exists === null ) { // error?
967 $res = null; // if we don't find anything, it is indeterminate
975 * @see FileBackendStore::directoryExists()
977 * @param string $container Resolved container name
978 * @param string $dir Resolved path relative to container
979 * @param array $params
982 abstract protected function doDirectoryExists( $container, $dir, array $params );
985 * @see FileBackend::getDirectoryList()
986 * @return Traversable|Array|null Returns null on failure
988 final public function getDirectoryList( array $params ) {
989 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
990 if ( $dir === null ) { // invalid storage path
993 if ( $shard !== null ) {
994 // File listing is confined to a single container/shard
995 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
997 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
998 // File listing spans multiple containers/shards
999 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
1000 return new FileBackendStoreShardDirIterator( $this,
1001 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
1006 * Do not call this function from places outside FileBackend
1008 * @see FileBackendStore::getDirectoryList()
1010 * @param string $container Resolved container name
1011 * @param string $dir Resolved path relative to container
1012 * @param array $params
1013 * @return Traversable|Array|null Returns null on failure
1015 abstract public function getDirectoryListInternal( $container, $dir, array $params );
1018 * @see FileBackend::getFileList()
1019 * @return Traversable|Array|null Returns null on failure
1021 final public function getFileList( array $params ) {
1022 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
1023 if ( $dir === null ) { // invalid storage path
1026 if ( $shard !== null ) {
1027 // File listing is confined to a single container/shard
1028 return $this->getFileListInternal( $fullCont, $dir, $params );
1030 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
1031 // File listing spans multiple containers/shards
1032 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
1033 return new FileBackendStoreShardFileIterator( $this,
1034 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
1039 * Do not call this function from places outside FileBackend
1041 * @see FileBackendStore::getFileList()
1043 * @param string $container Resolved container name
1044 * @param string $dir Resolved path relative to container
1045 * @param array $params
1046 * @return Traversable|Array|null Returns null on failure
1048 abstract public function getFileListInternal( $container, $dir, array $params );
1051 * Return a list of FileOp objects from a list of operations.
1052 * Do not call this function from places outside FileBackend.
1054 * The result must have the same number of items as the input.
1055 * An exception is thrown if an unsupported operation is requested.
1057 * @param array $ops Same format as doOperations()
1058 * @return Array List of FileOp objects
1059 * @throws MWException
1061 final public function getOperationsInternal( array $ops ) {
1062 $supportedOps = array(
1063 'store' => 'StoreFileOp',
1064 'copy' => 'CopyFileOp',
1065 'move' => 'MoveFileOp',
1066 'delete' => 'DeleteFileOp',
1067 'create' => 'CreateFileOp',
1068 'describe' => 'DescribeFileOp',
1069 'null' => 'NullFileOp'
1072 $performOps = array(); // array of FileOp objects
1073 // Build up ordered array of FileOps...
1074 foreach ( $ops as $operation ) {
1075 $opName = $operation['op'];
1076 if ( isset( $supportedOps[$opName] ) ) {
1077 $class = $supportedOps[$opName];
1078 // Get params for this operation
1079 $params = $operation;
1080 // Append the FileOp class
1081 $performOps[] = new $class( $this, $params );
1083 throw new MWException( "Operation '$opName' is not supported." );
1091 * Get a list of storage paths to lock for a list of operations
1092 * Returns an array with 'sh' (shared) and 'ex' (exclusive) keys,
1093 * each corresponding to a list of storage paths to be locked.
1094 * All returned paths are normalized.
1096 * @param array $performOps List of FileOp objects
1097 * @return Array ('sh' => list of paths, 'ex' => list of paths)
1099 final public function getPathsToLockForOpsInternal( array $performOps ) {
1100 // Build up a list of files to lock...
1101 $paths = array( 'sh' => array(), 'ex' => array() );
1102 foreach ( $performOps as $fileOp ) {
1103 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1104 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1106 // Optimization: if doing an EX lock anyway, don't also set an SH one
1107 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1108 // Get a shared lock on the parent directory of each path changed
1109 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1115 * @see FileBackend::getScopedLocksForOps()
1118 public function getScopedLocksForOps( array $ops, Status
$status ) {
1119 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1121 $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status ),
1122 $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status )
1127 * @see FileBackend::doOperationsInternal()
1130 final protected function doOperationsInternal( array $ops, array $opts ) {
1131 wfProfileIn( __METHOD__
);
1132 wfProfileIn( __METHOD__
. '-' . $this->name
);
1133 $status = Status
::newGood();
1135 // Fix up custom header name/value pairs...
1136 $ops = array_map( array( $this, 'stripInvalidHeadersFromOp' ), $ops );
1138 // Build up a list of FileOps...
1139 $performOps = $this->getOperationsInternal( $ops );
1141 // Acquire any locks as needed...
1142 if ( empty( $opts['nonLocking'] ) ) {
1143 // Build up a list of files to lock...
1144 $paths = $this->getPathsToLockForOpsInternal( $performOps );
1145 // Try to lock those files for the scope of this function...
1146 $scopeLockS = $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status );
1147 $scopeLockE = $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status );
1148 if ( !$status->isOK() ) {
1149 wfProfileOut( __METHOD__
. '-' . $this->name
);
1150 wfProfileOut( __METHOD__
);
1151 return $status; // abort
1155 // Clear any file cache entries (after locks acquired)
1156 if ( empty( $opts['preserveCache'] ) ) {
1157 $this->clearCache();
1160 // Load from the persistent file and container caches
1161 $this->primeFileCache( $performOps );
1162 $this->primeContainerCache( $performOps );
1164 // Actually attempt the operation batch...
1165 $opts = $this->setConcurrencyFlags( $opts );
1166 $subStatus = FileOpBatch
::attempt( $performOps, $opts, $this->fileJournal
);
1168 // Merge errors into status fields
1169 $status->merge( $subStatus );
1170 $status->success
= $subStatus->success
; // not done in merge()
1172 wfProfileOut( __METHOD__
. '-' . $this->name
);
1173 wfProfileOut( __METHOD__
);
1178 * @see FileBackend::doQuickOperationsInternal()
1180 * @throws MWException
1182 final protected function doQuickOperationsInternal( array $ops ) {
1183 wfProfileIn( __METHOD__
);
1184 wfProfileIn( __METHOD__
. '-' . $this->name
);
1185 $status = Status
::newGood();
1187 // Fix up custom header name/value pairs...
1188 $ops = array_map( array( $this, 'stripInvalidHeadersFromOp' ), $ops );
1190 // Clear any file cache entries
1191 $this->clearCache();
1193 $supportedOps = array( 'create', 'store', 'copy', 'move', 'delete', 'null' );
1194 $async = ( $this->parallelize
=== 'implicit' );
1195 $maxConcurrency = $this->concurrency
; // throttle
1197 $statuses = array(); // array of (index => Status)
1198 $fileOpHandles = array(); // list of (index => handle) arrays
1199 $curFileOpHandles = array(); // current handle batch
1200 // Perform the sync-only ops and build up op handles for the async ops...
1201 foreach ( $ops as $index => $params ) {
1202 if ( !in_array( $params['op'], $supportedOps ) ) {
1203 wfProfileOut( __METHOD__
. '-' . $this->name
);
1204 wfProfileOut( __METHOD__
);
1205 throw new MWException( "Operation '{$params['op']}' is not supported." );
1207 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1208 $subStatus = $this->$method( array( 'async' => $async ) +
$params );
1209 if ( $subStatus->value
instanceof FileBackendStoreOpHandle
) { // async
1210 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1211 $fileOpHandles[] = $curFileOpHandles; // push this batch
1212 $curFileOpHandles = array();
1214 $curFileOpHandles[$index] = $subStatus->value
; // keep index
1215 } else { // error or completed
1216 $statuses[$index] = $subStatus; // keep index
1219 if ( count( $curFileOpHandles ) ) {
1220 $fileOpHandles[] = $curFileOpHandles; // last batch
1222 // Do all the async ops that can be done concurrently...
1223 foreach ( $fileOpHandles as $fileHandleBatch ) {
1224 $statuses = $statuses +
$this->executeOpHandlesInternal( $fileHandleBatch );
1226 // Marshall and merge all the responses...
1227 foreach ( $statuses as $index => $subStatus ) {
1228 $status->merge( $subStatus );
1229 if ( $subStatus->isOK() ) {
1230 $status->success
[$index] = true;
1231 ++
$status->successCount
;
1233 $status->success
[$index] = false;
1234 ++
$status->failCount
;
1238 wfProfileOut( __METHOD__
. '-' . $this->name
);
1239 wfProfileOut( __METHOD__
);
1244 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1245 * The resulting Status object fields will correspond
1246 * to the order in which the handles where given.
1248 * @param array $handles List of FileBackendStoreOpHandle objects
1249 * @return Array Map of Status objects
1250 * @throws MWException
1252 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1253 wfProfileIn( __METHOD__
);
1254 wfProfileIn( __METHOD__
. '-' . $this->name
);
1255 foreach ( $fileOpHandles as $fileOpHandle ) {
1256 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle
) ) {
1257 wfProfileOut( __METHOD__
. '-' . $this->name
);
1258 wfProfileOut( __METHOD__
);
1259 throw new MWException( "Given a non-FileBackendStoreOpHandle object." );
1260 } elseif ( $fileOpHandle->backend
->getName() !== $this->getName() ) {
1261 wfProfileOut( __METHOD__
. '-' . $this->name
);
1262 wfProfileOut( __METHOD__
);
1263 throw new MWException( "Given a FileBackendStoreOpHandle for the wrong backend." );
1266 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1267 foreach ( $fileOpHandles as $fileOpHandle ) {
1268 $fileOpHandle->closeResources();
1270 wfProfileOut( __METHOD__
. '-' . $this->name
);
1271 wfProfileOut( __METHOD__
);
1276 * @see FileBackendStore::executeOpHandlesInternal()
1277 * @param array $fileOpHandles
1278 * @throws MWException
1279 * @return Array List of corresponding Status objects
1281 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1282 foreach ( $fileOpHandles as $fileOpHandle ) { // OK if empty
1283 throw new MWException( "This backend supports no asynchronous operations." );
1289 * Strip long HTTP headers from a file operation.
1290 * Most headers are just numbers, but some are allowed to be long.
1291 * This function is useful for cleaning up headers and avoiding backend
1292 * specific errors, especially in the middle of batch file operations.
1294 * @param array $op Same format as doOperation()
1297 protected function stripInvalidHeadersFromOp( array $op ) {
1298 static $longs = array( 'Content-Disposition' );
1299 if ( isset( $op['headers'] ) ) { // op sets HTTP headers
1300 foreach ( $op['headers'] as $name => $value ) {
1301 $maxHVLen = in_array( $name, $longs ) ? INF
: 255;
1302 if ( strlen( $name ) > 255 ||
strlen( $value ) > $maxHVLen ) {
1303 trigger_error( "Header '$name: $value' is too long." );
1304 unset( $op['headers'][$name] );
1305 } elseif ( !strlen( $value ) ) {
1306 $op['headers'][$name] = ''; // null/false => ""
1314 * @see FileBackend::preloadCache()
1316 final public function preloadCache( array $paths ) {
1317 $fullConts = array(); // full container names
1318 foreach ( $paths as $path ) {
1319 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1320 $fullConts[] = $fullCont;
1322 // Load from the persistent file and container caches
1323 $this->primeContainerCache( $fullConts );
1324 $this->primeFileCache( $paths );
1328 * @see FileBackend::clearCache()
1330 final public function clearCache( array $paths = null ) {
1331 if ( is_array( $paths ) ) {
1332 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1333 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1335 if ( $paths === null ) {
1336 $this->cheapCache
->clear();
1337 $this->expensiveCache
->clear();
1339 foreach ( $paths as $path ) {
1340 $this->cheapCache
->clear( $path );
1341 $this->expensiveCache
->clear( $path );
1344 $this->doClearCache( $paths );
1348 * Clears any additional stat caches for storage paths
1350 * @see FileBackend::clearCache()
1352 * @param array $paths Storage paths (optional)
1355 protected function doClearCache( array $paths = null ) {}
1358 * Is this a key/value store where directories are just virtual?
1359 * Virtual directories exists in so much as files exists that are
1360 * prefixed with the directory path followed by a forward slash.
1364 abstract protected function directoriesAreVirtual();
1367 * Check if a container name is valid.
1368 * This checks for for length and illegal characters.
1370 * @param $container string
1373 final protected static function isValidContainerName( $container ) {
1374 // This accounts for Swift and S3 restrictions while leaving room
1375 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1376 // This disallows directory separators or traversal characters.
1377 // Note that matching strings URL encode to the same string;
1378 // in Swift, the length restriction is *after* URL encoding.
1379 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1383 * Splits a storage path into an internal container name,
1384 * an internal relative file name, and a container shard suffix.
1385 * Any shard suffix is already appended to the internal container name.
1386 * This also checks that the storage path is valid and within this backend.
1388 * If the container is sharded but a suffix could not be determined,
1389 * this means that the path can only refer to a directory and can only
1390 * be scanned by looking in all the container shards.
1392 * @param $storagePath string
1393 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1395 final protected function resolveStoragePath( $storagePath ) {
1396 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1397 if ( $backend === $this->name
) { // must be for this backend
1398 $relPath = self
::normalizeContainerPath( $relPath );
1399 if ( $relPath !== null ) {
1400 // Get shard for the normalized path if this container is sharded
1401 $cShard = $this->getContainerShard( $container, $relPath );
1402 // Validate and sanitize the relative path (backend-specific)
1403 $relPath = $this->resolveContainerPath( $container, $relPath );
1404 if ( $relPath !== null ) {
1405 // Prepend any wiki ID prefix to the container name
1406 $container = $this->fullContainerName( $container );
1407 if ( self
::isValidContainerName( $container ) ) {
1408 // Validate and sanitize the container name (backend-specific)
1409 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1410 if ( $container !== null ) {
1411 return array( $container, $relPath, $cShard );
1417 return array( null, null, null );
1421 * Like resolveStoragePath() except null values are returned if
1422 * the container is sharded and the shard could not be determined
1423 * or if the path ends with '/'. The later case is illegal for FS
1424 * backends and can confuse listings for object store backends.
1426 * This function is used when resolving paths that must be valid
1427 * locations for files. Directory and listing functions should
1428 * generally just use resolveStoragePath() instead.
1430 * @see FileBackendStore::resolveStoragePath()
1432 * @param $storagePath string
1433 * @return Array (container, path) or (null, null) if invalid
1435 final protected function resolveStoragePathReal( $storagePath ) {
1436 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1437 if ( $cShard !== null && substr( $relPath, -1 ) !== '/' ) {
1438 return array( $container, $relPath );
1440 return array( null, null );
1444 * Get the container name shard suffix for a given path.
1445 * Any empty suffix means the container is not sharded.
1447 * @param string $container Container name
1448 * @param string $relPath Storage path relative to the container
1449 * @return string|null Returns null if shard could not be determined
1451 final protected function getContainerShard( $container, $relPath ) {
1452 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1453 if ( $levels == 1 ||
$levels == 2 ) {
1454 // Hash characters are either base 16 or 36
1455 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1456 // Get a regex that represents the shard portion of paths.
1457 // The concatenation of the captures gives us the shard.
1458 if ( $levels === 1 ) { // 16 or 36 shards per container
1459 $hashDirRegex = '(' . $char . ')';
1460 } else { // 256 or 1296 shards per container
1461 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1462 $hashDirRegex = $char . '/(' . $char . '{2})';
1463 } else { // short hash dir format (e.g. "a/b/c")
1464 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1467 // Allow certain directories to be above the hash dirs so as
1468 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1469 // They must be 2+ chars to avoid any hash directory ambiguity.
1471 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1472 return '.' . implode( '', array_slice( $m, 1 ) );
1474 return null; // failed to match
1476 return ''; // no sharding
1480 * Check if a storage path maps to a single shard.
1481 * Container dirs like "a", where the container shards on "x/xy",
1482 * can reside on several shards. Such paths are tricky to handle.
1484 * @param string $storagePath Storage path
1487 final public function isSingleShardPathInternal( $storagePath ) {
1488 list( , , $shard ) = $this->resolveStoragePath( $storagePath );
1489 return ( $shard !== null );
1493 * Get the sharding config for a container.
1494 * If greater than 0, then all file storage paths within
1495 * the container are required to be hashed accordingly.
1497 * @param $container string
1498 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
1500 final protected function getContainerHashLevels( $container ) {
1501 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1502 $config = $this->shardViaHashLevels
[$container];
1503 $hashLevels = (int)$config['levels'];
1504 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1505 $hashBase = (int)$config['base'];
1506 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1507 return array( $hashLevels, $hashBase, $config['repeat'] );
1511 return array( 0, 0, false ); // no sharding
1515 * Get a list of full container shard suffixes for a container
1517 * @param $container string
1520 final protected function getContainerSuffixes( $container ) {
1522 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1523 if ( $digits > 0 ) {
1524 $numShards = pow( $base, $digits );
1525 for ( $index = 0; $index < $numShards; $index++
) {
1526 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1533 * Get the full container name, including the wiki ID prefix
1535 * @param $container string
1538 final protected function fullContainerName( $container ) {
1539 if ( $this->wikiId
!= '' ) {
1540 return "{$this->wikiId}-$container";
1547 * Resolve a container name, checking if it's allowed by the backend.
1548 * This is intended for internal use, such as encoding illegal chars.
1549 * Subclasses can override this to be more restrictive.
1551 * @param $container string
1552 * @return string|null
1554 protected function resolveContainerName( $container ) {
1559 * Resolve a relative storage path, checking if it's allowed by the backend.
1560 * This is intended for internal use, such as encoding illegal chars or perhaps
1561 * getting absolute paths (e.g. FS based backends). Note that the relative path
1562 * may be the empty string (e.g. the path is simply to the container).
1564 * @param string $container Container name
1565 * @param string $relStoragePath Storage path relative to the container
1566 * @return string|null Path or null if not valid
1568 protected function resolveContainerPath( $container, $relStoragePath ) {
1569 return $relStoragePath;
1573 * Get the cache key for a container
1575 * @param string $container Resolved container name
1578 private function containerCacheKey( $container ) {
1579 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1583 * Set the cached info for a container
1585 * @param string $container Resolved container name
1586 * @param array $val Information to cache
1589 final protected function setContainerCache( $container, array $val ) {
1590 $this->memCache
->add( $this->containerCacheKey( $container ), $val, 14 * 86400 );
1594 * Delete the cached info for a container.
1595 * The cache key is salted for a while to prevent race conditions.
1597 * @param string $container Resolved container name
1600 final protected function deleteContainerCache( $container ) {
1601 if ( !$this->memCache
->set( $this->containerCacheKey( $container ), 'PURGED', 300 ) ) {
1602 trigger_error( "Unable to delete stat cache for container $container." );
1607 * Do a batch lookup from cache for container stats for all containers
1608 * used in a list of container names, storage paths, or FileOp objects.
1609 * This loads the persistent cache values into the process cache.
1611 * @param $items Array
1614 final protected function primeContainerCache( array $items ) {
1615 wfProfileIn( __METHOD__
);
1616 wfProfileIn( __METHOD__
. '-' . $this->name
);
1618 $paths = array(); // list of storage paths
1619 $contNames = array(); // (cache key => resolved container name)
1620 // Get all the paths/containers from the items...
1621 foreach ( $items as $item ) {
1622 if ( $item instanceof FileOp
) {
1623 $paths = array_merge( $paths, $item->storagePathsRead() );
1624 $paths = array_merge( $paths, $item->storagePathsChanged() );
1625 } elseif ( self
::isStoragePath( $item ) ) {
1627 } elseif ( is_string( $item ) ) { // full container name
1628 $contNames[$this->containerCacheKey( $item )] = $item;
1631 // Get all the corresponding cache keys for paths...
1632 foreach ( $paths as $path ) {
1633 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1634 if ( $fullCont !== null ) { // valid path for this backend
1635 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1639 $contInfo = array(); // (resolved container name => cache value)
1640 // Get all cache entries for these container cache keys...
1641 $values = $this->memCache
->getMulti( array_keys( $contNames ) );
1642 foreach ( $values as $cacheKey => $val ) {
1643 $contInfo[$contNames[$cacheKey]] = $val;
1646 // Populate the container process cache for the backend...
1647 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1649 wfProfileOut( __METHOD__
. '-' . $this->name
);
1650 wfProfileOut( __METHOD__
);
1654 * Fill the backend-specific process cache given an array of
1655 * resolved container names and their corresponding cached info.
1656 * Only containers that actually exist should appear in the map.
1658 * @param array $containerInfo Map of resolved container names to cached info
1661 protected function doPrimeContainerCache( array $containerInfo ) {}
1664 * Get the cache key for a file path
1666 * @param string $path Normalized storage path
1669 private function fileCacheKey( $path ) {
1670 return wfMemcKey( 'backend', $this->getName(), 'file', sha1( $path ) );
1674 * Set the cached stat info for a file path.
1675 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1676 * salting for the case when a file is created at a path were there was none before.
1678 * @param string $path Storage path
1679 * @param array $val Stat information to cache
1682 final protected function setFileCache( $path, array $val ) {
1683 $path = FileBackend
::normalizeStoragePath( $path );
1684 if ( $path === null ) {
1685 return; // invalid storage path
1687 $age = time() - wfTimestamp( TS_UNIX
, $val['mtime'] );
1688 $ttl = min( 7 * 86400, max( 300, floor( .1 * $age ) ) );
1689 $this->memCache
->add( $this->fileCacheKey( $path ), $val, $ttl );
1693 * Delete the cached stat info for a file path.
1694 * The cache key is salted for a while to prevent race conditions.
1695 * Since negatives (404s) are not cached, this does not need to be called when
1696 * a file is created at a path were there was none before.
1698 * @param string $path Storage path
1701 final protected function deleteFileCache( $path ) {
1702 $path = FileBackend
::normalizeStoragePath( $path );
1703 if ( $path === null ) {
1704 return; // invalid storage path
1706 if ( !$this->memCache
->set( $this->fileCacheKey( $path ), 'PURGED', 300 ) ) {
1707 trigger_error( "Unable to delete stat cache for file $path." );
1712 * Do a batch lookup from cache for file stats for all paths
1713 * used in a list of storage paths or FileOp objects.
1714 * This loads the persistent cache values into the process cache.
1716 * @param array $items List of storage paths or FileOps
1719 final protected function primeFileCache( array $items ) {
1720 wfProfileIn( __METHOD__
);
1721 wfProfileIn( __METHOD__
. '-' . $this->name
);
1723 $paths = array(); // list of storage paths
1724 $pathNames = array(); // (cache key => storage path)
1725 // Get all the paths/containers from the items...
1726 foreach ( $items as $item ) {
1727 if ( $item instanceof FileOp
) {
1728 $paths = array_merge( $paths, $item->storagePathsRead() );
1729 $paths = array_merge( $paths, $item->storagePathsChanged() );
1730 } elseif ( self
::isStoragePath( $item ) ) {
1731 $paths[] = FileBackend
::normalizeStoragePath( $item );
1734 // Get rid of any paths that failed normalization...
1735 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1736 // Get all the corresponding cache keys for paths...
1737 foreach ( $paths as $path ) {
1738 list( , $rel, ) = $this->resolveStoragePath( $path );
1739 if ( $rel !== null ) { // valid path for this backend
1740 $pathNames[$this->fileCacheKey( $path )] = $path;
1743 // Get all cache entries for these container cache keys...
1744 $values = $this->memCache
->getMulti( array_keys( $pathNames ) );
1745 foreach ( $values as $cacheKey => $val ) {
1746 if ( is_array( $val ) ) {
1747 $path = $pathNames[$cacheKey];
1748 $this->cheapCache
->set( $path, 'stat', $val );
1749 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1750 $this->cheapCache
->set( $path, 'sha1',
1751 array( 'hash' => $val['sha1'], 'latest' => $val['latest'] ) );
1756 wfProfileOut( __METHOD__
. '-' . $this->name
);
1757 wfProfileOut( __METHOD__
);
1761 * Set the 'concurrency' option from a list of operation options
1763 * @param array $opts Map of operation options
1766 final protected function setConcurrencyFlags( array $opts ) {
1767 $opts['concurrency'] = 1; // off
1768 if ( $this->parallelize
=== 'implicit' ) {
1769 if ( !isset( $opts['parallelize'] ) ||
$opts['parallelize'] ) {
1770 $opts['concurrency'] = $this->concurrency
;
1772 } elseif ( $this->parallelize
=== 'explicit' ) {
1773 if ( !empty( $opts['parallelize'] ) ) {
1774 $opts['concurrency'] = $this->concurrency
;
1782 * FileBackendStore helper class for performing asynchronous file operations.
1784 * For example, calling FileBackendStore::createInternal() with the "async"
1785 * param flag may result in a Status that contains this object as a value.
1786 * This class is largely backend-specific and is mostly just "magic" to be
1787 * passed to FileBackendStore::executeOpHandlesInternal().
1789 abstract class FileBackendStoreOpHandle
{
1791 public $params = array(); // params to caller functions
1792 /** @var FileBackendStore */
1795 public $resourcesToClose = array();
1797 public $call; // string; name that identifies the function called
1800 * Close all open file handles
1804 public function closeResources() {
1805 array_map( 'fclose', $this->resourcesToClose
);
1810 * FileBackendStore helper function to handle listings that span container shards.
1811 * Do not use this class from places outside of FileBackendStore.
1813 * @ingroup FileBackend
1815 abstract class FileBackendStoreShardListIterator
extends FilterIterator
{
1816 /** @var FileBackendStore */
1821 protected $container; // string; full container name
1822 protected $directory; // string; resolved relative path
1825 protected $multiShardPaths = array(); // (rel path => 1)
1828 * @param $backend FileBackendStore
1829 * @param string $container Full storage container name
1830 * @param string $dir Storage directory relative to container
1831 * @param array $suffixes List of container shard suffixes
1832 * @param array $params
1834 public function __construct(
1835 FileBackendStore
$backend, $container, $dir, array $suffixes, array $params
1837 $this->backend
= $backend;
1838 $this->container
= $container;
1839 $this->directory
= $dir;
1840 $this->params
= $params;
1842 $iter = new AppendIterator();
1843 foreach ( $suffixes as $suffix ) {
1844 $iter->append( $this->listFromShard( $this->container
. $suffix ) );
1847 parent
::__construct( $iter );
1850 public function accept() {
1851 $rel = $this->getInnerIterator()->current(); // path relative to given directory
1852 $path = $this->params
['dir'] . "/{$rel}"; // full storage path
1853 if ( $this->backend
->isSingleShardPathInternal( $path ) ) {
1854 return true; // path is only on one shard; no issue with duplicates
1855 } elseif ( isset( $this->multiShardPaths
[$rel] ) ) {
1856 // Don't keep listing paths that are on multiple shards
1859 $this->multiShardPaths
[$rel] = 1;
1864 public function rewind() {
1866 $this->multiShardPaths
= array();
1870 * Get the list for a given container shard
1872 * @param string $container Resolved container name
1875 abstract protected function listFromShard( $container );
1879 * Iterator for listing directories
1881 class FileBackendStoreShardDirIterator
extends FileBackendStoreShardListIterator
{
1882 protected function listFromShard( $container ) {
1883 $list = $this->backend
->getDirectoryListInternal(
1884 $container, $this->directory
, $this->params
);
1885 if ( $list === null ) {
1886 return new ArrayIterator( array() );
1888 return is_array( $list ) ?
new ArrayIterator( $list ) : $list;
1894 * Iterator for listing regular files
1896 class FileBackendStoreShardFileIterator
extends FileBackendStoreShardListIterator
{
1897 protected function listFromShard( $container ) {
1898 $list = $this->backend
->getFileListInternal(
1899 $container, $this->directory
, $this->params
);
1900 if ( $list === null ) {
1901 return new ArrayIterator( array() );
1903 return is_array( $list ) ?
new ArrayIterator( $list ) : $list;