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 $config Array
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 $storagePath string
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();
342 * @see FileBackend::concatenate()
345 final public function concatenate( array $params ) {
346 wfProfileIn( __METHOD__
);
347 wfProfileIn( __METHOD__
. '-' . $this->name
);
348 $status = Status
::newGood();
350 // Try to lock the source files for the scope of this function
351 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager
::LOCK_UW
, $status );
352 if ( $status->isOK() ) {
353 // Actually do the file concatenation...
354 $start_time = microtime( true );
355 $status->merge( $this->doConcatenate( $params ) );
356 $sec = microtime( true ) - $start_time;
357 if ( !$status->isOK() ) {
358 wfDebugLog( 'FileOperation', get_class( $this ) . " failed to concatenate " .
359 count( $params['srcs'] ) . " file(s) [$sec sec]" );
363 wfProfileOut( __METHOD__
. '-' . $this->name
);
364 wfProfileOut( __METHOD__
);
369 * @see FileBackendStore::concatenate()
372 protected function doConcatenate( array $params ) {
373 $status = Status
::newGood();
374 $tmpPath = $params['dst']; // convenience
375 unset( $params['latest'] ); // sanity
377 // Check that the specified temp file is valid...
378 wfSuppressWarnings();
379 $ok = ( is_file( $tmpPath ) && filesize( $tmpPath ) == 0 );
381 if ( !$ok ) { // not present or not empty
382 $status->fatal( 'backend-fail-opentemp', $tmpPath );
386 // Get local FS versions of the chunks needed for the concatenation...
387 $fsFiles = $this->getLocalReferenceMulti( $params );
388 foreach ( $fsFiles as $path => &$fsFile ) {
389 if ( !$fsFile ) { // chunk failed to download?
390 $fsFile = $this->getLocalReference( array( 'src' => $path ) );
391 if ( !$fsFile ) { // retry failed?
392 $status->fatal( 'backend-fail-read', $path );
397 unset( $fsFile ); // unset reference so we can reuse $fsFile
399 // Get a handle for the destination temp file
400 $tmpHandle = fopen( $tmpPath, 'ab' );
401 if ( $tmpHandle === false ) {
402 $status->fatal( 'backend-fail-opentemp', $tmpPath );
406 // Build up the temp file using the source chunks (in order)...
407 foreach ( $fsFiles as $virtualSource => $fsFile ) {
408 // Get a handle to the local FS version
409 $sourceHandle = fopen( $fsFile->getPath(), 'rb' );
410 if ( $sourceHandle === false ) {
411 fclose( $tmpHandle );
412 $status->fatal( 'backend-fail-read', $virtualSource );
415 // Append chunk to file (pass chunk size to avoid magic quotes)
416 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
417 fclose( $sourceHandle );
418 fclose( $tmpHandle );
419 $status->fatal( 'backend-fail-writetemp', $tmpPath );
422 fclose( $sourceHandle );
424 if ( !fclose( $tmpHandle ) ) {
425 $status->fatal( 'backend-fail-closetemp', $tmpPath );
429 clearstatcache(); // temp file changed
435 * @see FileBackend::doPrepare()
438 final protected function doPrepare( array $params ) {
439 wfProfileIn( __METHOD__
);
440 wfProfileIn( __METHOD__
. '-' . $this->name
);
442 $status = Status
::newGood();
443 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
444 if ( $dir === null ) {
445 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
446 wfProfileOut( __METHOD__
. '-' . $this->name
);
447 wfProfileOut( __METHOD__
);
448 return $status; // invalid storage path
451 if ( $shard !== null ) { // confined to a single container/shard
452 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
453 } else { // directory is on several shards
454 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
455 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
456 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
457 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
461 wfProfileOut( __METHOD__
. '-' . $this->name
);
462 wfProfileOut( __METHOD__
);
467 * @see FileBackendStore::doPrepare()
470 protected function doPrepareInternal( $container, $dir, array $params ) {
471 return Status
::newGood();
475 * @see FileBackend::doSecure()
478 final protected function doSecure( array $params ) {
479 wfProfileIn( __METHOD__
);
480 wfProfileIn( __METHOD__
. '-' . $this->name
);
481 $status = Status
::newGood();
483 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
484 if ( $dir === null ) {
485 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
486 wfProfileOut( __METHOD__
. '-' . $this->name
);
487 wfProfileOut( __METHOD__
);
488 return $status; // invalid storage path
491 if ( $shard !== null ) { // confined to a single container/shard
492 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
493 } else { // directory is on several shards
494 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
495 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
496 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
497 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
501 wfProfileOut( __METHOD__
. '-' . $this->name
);
502 wfProfileOut( __METHOD__
);
507 * @see FileBackendStore::doSecure()
510 protected function doSecureInternal( $container, $dir, array $params ) {
511 return Status
::newGood();
515 * @see FileBackend::doPublish()
518 final protected function doPublish( array $params ) {
519 wfProfileIn( __METHOD__
);
520 wfProfileIn( __METHOD__
. '-' . $this->name
);
521 $status = Status
::newGood();
523 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
524 if ( $dir === null ) {
525 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
526 wfProfileOut( __METHOD__
. '-' . $this->name
);
527 wfProfileOut( __METHOD__
);
528 return $status; // invalid storage path
531 if ( $shard !== null ) { // confined to a single container/shard
532 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
533 } else { // directory is on several shards
534 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
535 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
536 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
537 $status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
541 wfProfileOut( __METHOD__
. '-' . $this->name
);
542 wfProfileOut( __METHOD__
);
547 * @see FileBackendStore::doPublish()
550 protected function doPublishInternal( $container, $dir, array $params ) {
551 return Status
::newGood();
555 * @see FileBackend::doClean()
558 final protected function doClean( array $params ) {
559 wfProfileIn( __METHOD__
);
560 wfProfileIn( __METHOD__
. '-' . $this->name
);
561 $status = Status
::newGood();
563 // Recursive: first delete all empty subdirs recursively
564 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
565 $subDirsRel = $this->getTopDirectoryList( array( 'dir' => $params['dir'] ) );
566 if ( $subDirsRel !== null ) { // no errors
567 foreach ( $subDirsRel as $subDirRel ) {
568 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
569 $status->merge( $this->doClean( array( 'dir' => $subDir ) +
$params ) );
571 unset( $subDirsRel ); // free directory for rmdir() on Windows (for FS backends)
575 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
576 if ( $dir === null ) {
577 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
578 wfProfileOut( __METHOD__
. '-' . $this->name
);
579 wfProfileOut( __METHOD__
);
580 return $status; // invalid storage path
583 // Attempt to lock this directory...
584 $filesLockEx = array( $params['dir'] );
585 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
586 if ( !$status->isOK() ) {
587 wfProfileOut( __METHOD__
. '-' . $this->name
);
588 wfProfileOut( __METHOD__
);
589 return $status; // abort
592 if ( $shard !== null ) { // confined to a single container/shard
593 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
594 $this->deleteContainerCache( $fullCont ); // purge cache
595 } else { // directory is on several shards
596 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
597 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
598 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
599 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
600 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
604 wfProfileOut( __METHOD__
. '-' . $this->name
);
605 wfProfileOut( __METHOD__
);
610 * @see FileBackendStore::doClean()
613 protected function doCleanInternal( $container, $dir, array $params ) {
614 return Status
::newGood();
618 * @see FileBackend::fileExists()
621 final public function fileExists( array $params ) {
622 wfProfileIn( __METHOD__
);
623 wfProfileIn( __METHOD__
. '-' . $this->name
);
624 $stat = $this->getFileStat( $params );
625 wfProfileOut( __METHOD__
. '-' . $this->name
);
626 wfProfileOut( __METHOD__
);
627 return ( $stat === null ) ?
null : (bool)$stat; // null => failure
631 * @see FileBackend::getFileTimestamp()
634 final public function getFileTimestamp( array $params ) {
635 wfProfileIn( __METHOD__
);
636 wfProfileIn( __METHOD__
. '-' . $this->name
);
637 $stat = $this->getFileStat( $params );
638 wfProfileOut( __METHOD__
. '-' . $this->name
);
639 wfProfileOut( __METHOD__
);
640 return $stat ?
$stat['mtime'] : false;
644 * @see FileBackend::getFileSize()
647 final public function getFileSize( array $params ) {
648 wfProfileIn( __METHOD__
);
649 wfProfileIn( __METHOD__
. '-' . $this->name
);
650 $stat = $this->getFileStat( $params );
651 wfProfileOut( __METHOD__
. '-' . $this->name
);
652 wfProfileOut( __METHOD__
);
653 return $stat ?
$stat['size'] : false;
657 * @see FileBackend::getFileStat()
660 final public function getFileStat( array $params ) {
661 $path = self
::normalizeStoragePath( $params['src'] );
662 if ( $path === null ) {
663 return false; // invalid storage path
665 wfProfileIn( __METHOD__
);
666 wfProfileIn( __METHOD__
. '-' . $this->name
);
667 $latest = !empty( $params['latest'] ); // use latest data?
668 if ( !$this->cheapCache
->has( $path, 'stat', self
::CACHE_TTL
) ) {
669 $this->primeFileCache( array( $path ) ); // check persistent cache
671 if ( $this->cheapCache
->has( $path, 'stat', self
::CACHE_TTL
) ) {
672 $stat = $this->cheapCache
->get( $path, 'stat' );
673 // If we want the latest data, check that this cached
674 // value was in fact fetched with the latest available data.
675 if ( is_array( $stat ) ) {
676 if ( !$latest ||
$stat['latest'] ) {
677 wfProfileOut( __METHOD__
. '-' . $this->name
);
678 wfProfileOut( __METHOD__
);
681 } elseif ( in_array( $stat, array( 'NOT_EXIST', 'NOT_EXIST_LATEST' ) ) ) {
682 if ( !$latest ||
$stat === 'NOT_EXIST_LATEST' ) {
683 wfProfileOut( __METHOD__
. '-' . $this->name
);
684 wfProfileOut( __METHOD__
);
689 wfProfileIn( __METHOD__
. '-miss' );
690 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
691 $stat = $this->doGetFileStat( $params );
692 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
693 wfProfileOut( __METHOD__
. '-miss' );
694 if ( is_array( $stat ) ) { // file exists
695 $stat['latest'] = $latest;
696 $this->cheapCache
->set( $path, 'stat', $stat );
697 $this->setFileCache( $path, $stat ); // update persistent cache
698 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
699 $this->cheapCache
->set( $path, 'sha1',
700 array( 'hash' => $stat['sha1'], 'latest' => $latest ) );
702 } elseif ( $stat === false ) { // file does not exist
703 $this->cheapCache
->set( $path, 'stat', $latest ?
'NOT_EXIST_LATEST' : 'NOT_EXIST' );
704 $this->cheapCache
->set( $path, 'sha1', // the SHA-1 must be false too
705 array( 'hash' => false, 'latest' => $latest ) );
706 wfDebug( __METHOD__
. ": File $path does not exist.\n" );
707 } else { // an error occurred
708 wfDebug( __METHOD__
. ": Could not stat file $path.\n" );
710 wfProfileOut( __METHOD__
. '-' . $this->name
);
711 wfProfileOut( __METHOD__
);
716 * @see FileBackendStore::getFileStat()
718 abstract protected function doGetFileStat( array $params );
721 * @see FileBackend::getFileContentsMulti()
724 public function getFileContentsMulti( array $params ) {
725 wfProfileIn( __METHOD__
);
726 wfProfileIn( __METHOD__
. '-' . $this->name
);
728 $params = $this->setConcurrencyFlags( $params );
729 $contents = $this->doGetFileContentsMulti( $params );
731 wfProfileOut( __METHOD__
. '-' . $this->name
);
732 wfProfileOut( __METHOD__
);
737 * @see FileBackendStore::getFileContentsMulti()
740 protected function doGetFileContentsMulti( array $params ) {
742 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
743 wfSuppressWarnings();
744 $contents[$path] = $fsFile ?
file_get_contents( $fsFile->getPath() ) : false;
751 * @see FileBackend::getFileSha1Base36()
752 * @return bool|string
754 final public function getFileSha1Base36( array $params ) {
755 $path = self
::normalizeStoragePath( $params['src'] );
756 if ( $path === null ) {
757 return false; // invalid storage path
759 wfProfileIn( __METHOD__
);
760 wfProfileIn( __METHOD__
. '-' . $this->name
);
761 $latest = !empty( $params['latest'] ); // use latest data?
762 if ( $this->cheapCache
->has( $path, 'sha1', self
::CACHE_TTL
) ) {
763 $stat = $this->cheapCache
->get( $path, 'sha1' );
764 // If we want the latest data, check that this cached
765 // value was in fact fetched with the latest available data.
766 if ( !$latest ||
$stat['latest'] ) {
767 wfProfileOut( __METHOD__
. '-' . $this->name
);
768 wfProfileOut( __METHOD__
);
769 return $stat['hash'];
772 wfProfileIn( __METHOD__
. '-miss' );
773 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
774 $hash = $this->doGetFileSha1Base36( $params );
775 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
776 wfProfileOut( __METHOD__
. '-miss' );
777 $this->cheapCache
->set( $path, 'sha1', array( 'hash' => $hash, 'latest' => $latest ) );
778 wfProfileOut( __METHOD__
. '-' . $this->name
);
779 wfProfileOut( __METHOD__
);
784 * @see FileBackendStore::getFileSha1Base36()
785 * @return bool|string
787 protected function doGetFileSha1Base36( array $params ) {
788 $fsFile = $this->getLocalReference( $params );
792 return $fsFile->getSha1Base36();
797 * @see FileBackend::getFileProps()
800 final public function getFileProps( array $params ) {
801 wfProfileIn( __METHOD__
);
802 wfProfileIn( __METHOD__
. '-' . $this->name
);
803 $fsFile = $this->getLocalReference( $params );
804 $props = $fsFile ?
$fsFile->getProps() : FSFile
::placeholderProps();
805 wfProfileOut( __METHOD__
. '-' . $this->name
);
806 wfProfileOut( __METHOD__
);
811 * @see FileBackend::getLocalReferenceMulti()
814 final public function getLocalReferenceMulti( array $params ) {
815 wfProfileIn( __METHOD__
);
816 wfProfileIn( __METHOD__
. '-' . $this->name
);
818 $params = $this->setConcurrencyFlags( $params );
820 $fsFiles = array(); // (path => FSFile)
821 $latest = !empty( $params['latest'] ); // use latest data?
822 // Reuse any files already in process cache...
823 foreach ( $params['srcs'] as $src ) {
824 $path = self
::normalizeStoragePath( $src );
825 if ( $path === null ) {
826 $fsFiles[$src] = null; // invalid storage path
827 } elseif ( $this->expensiveCache
->has( $path, 'localRef' ) ) {
828 $val = $this->expensiveCache
->get( $path, 'localRef' );
829 // If we want the latest data, check that this cached
830 // value was in fact fetched with the latest available data.
831 if ( !$latest ||
$val['latest'] ) {
832 $fsFiles[$src] = $val['object'];
836 // Fetch local references of any remaning files...
837 $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
838 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
839 $fsFiles[$path] = $fsFile;
840 if ( $fsFile ) { // update the process cache...
841 $this->expensiveCache
->set( $path, 'localRef',
842 array( 'object' => $fsFile, 'latest' => $latest ) );
846 wfProfileOut( __METHOD__
. '-' . $this->name
);
847 wfProfileOut( __METHOD__
);
852 * @see FileBackendStore::getLocalReferenceMulti()
855 protected function doGetLocalReferenceMulti( array $params ) {
856 return $this->doGetLocalCopyMulti( $params );
860 * @see FileBackend::getLocalCopyMulti()
863 final public function getLocalCopyMulti( array $params ) {
864 wfProfileIn( __METHOD__
);
865 wfProfileIn( __METHOD__
. '-' . $this->name
);
867 $params = $this->setConcurrencyFlags( $params );
868 $tmpFiles = $this->doGetLocalCopyMulti( $params );
870 wfProfileOut( __METHOD__
. '-' . $this->name
);
871 wfProfileOut( __METHOD__
);
876 * @see FileBackendStore::getLocalCopyMulti()
879 abstract protected function doGetLocalCopyMulti( array $params );
882 * @see FileBackend::getFileHttpUrl()
883 * @return string|null
885 public function getFileHttpUrl( array $params ) {
886 return null; // not supported
890 * @see FileBackend::streamFile()
893 final public function streamFile( array $params ) {
894 wfProfileIn( __METHOD__
);
895 wfProfileIn( __METHOD__
. '-' . $this->name
);
896 $status = Status
::newGood();
898 $info = $this->getFileStat( $params );
899 if ( !$info ) { // let StreamFile handle the 404
900 $status->fatal( 'backend-fail-notexists', $params['src'] );
903 // Set output buffer and HTTP headers for stream
904 $extraHeaders = isset( $params['headers'] ) ?
$params['headers'] : array();
905 $res = StreamFile
::prepareForStream( $params['src'], $info, $extraHeaders );
906 if ( $res == StreamFile
::NOT_MODIFIED
) {
907 // do nothing; client cache is up to date
908 } elseif ( $res == StreamFile
::READY_STREAM
) {
909 wfProfileIn( __METHOD__
. '-send' );
910 wfProfileIn( __METHOD__
. '-send-' . $this->name
);
911 $status = $this->doStreamFile( $params );
912 wfProfileOut( __METHOD__
. '-send-' . $this->name
);
913 wfProfileOut( __METHOD__
. '-send' );
914 if ( !$status->isOK() ) {
915 // Per bug 41113, nasty things can happen if bad cache entries get
916 // stuck in cache. It's also possible that this error can come up
917 // with simple race conditions. Clear out the stat cache to be safe.
918 $this->clearCache( array( $params['src'] ) );
919 $this->deleteFileCache( $params['src'] );
920 trigger_error( "Bad stat cache or race condition for file {$params['src']}." );
923 $status->fatal( 'backend-fail-stream', $params['src'] );
926 wfProfileOut( __METHOD__
. '-' . $this->name
);
927 wfProfileOut( __METHOD__
);
932 * @see FileBackendStore::streamFile()
935 protected function doStreamFile( array $params ) {
936 $status = Status
::newGood();
938 $fsFile = $this->getLocalReference( $params );
940 $status->fatal( 'backend-fail-stream', $params['src'] );
941 } elseif ( !readfile( $fsFile->getPath() ) ) {
942 $status->fatal( 'backend-fail-stream', $params['src'] );
949 * @see FileBackend::directoryExists()
952 final public function directoryExists( array $params ) {
953 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
954 if ( $dir === null ) {
955 return false; // invalid storage path
957 if ( $shard !== null ) { // confined to a single container/shard
958 return $this->doDirectoryExists( $fullCont, $dir, $params );
959 } else { // directory is on several shards
960 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
961 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
962 $res = false; // response
963 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
964 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
968 } elseif ( $exists === null ) { // error?
969 $res = null; // if we don't find anything, it is indeterminate
977 * @see FileBackendStore::directoryExists()
979 * @param string $container Resolved container name
980 * @param string $dir Resolved path relative to container
981 * @param array $params
984 abstract protected function doDirectoryExists( $container, $dir, array $params );
987 * @see FileBackend::getDirectoryList()
988 * @return Traversable|Array|null Returns null on failure
990 final public function getDirectoryList( array $params ) {
991 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
992 if ( $dir === null ) { // invalid storage path
995 if ( $shard !== null ) {
996 // File listing is confined to a single container/shard
997 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
999 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
1000 // File listing spans multiple containers/shards
1001 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
1002 return new FileBackendStoreShardDirIterator( $this,
1003 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
1008 * Do not call this function from places outside FileBackend
1010 * @see FileBackendStore::getDirectoryList()
1012 * @param string $container Resolved container name
1013 * @param string $dir Resolved path relative to container
1014 * @param array $params
1015 * @return Traversable|Array|null Returns null on failure
1017 abstract public function getDirectoryListInternal( $container, $dir, array $params );
1020 * @see FileBackend::getFileList()
1021 * @return Traversable|Array|null Returns null on failure
1023 final public function getFileList( array $params ) {
1024 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
1025 if ( $dir === null ) { // invalid storage path
1028 if ( $shard !== null ) {
1029 // File listing is confined to a single container/shard
1030 return $this->getFileListInternal( $fullCont, $dir, $params );
1032 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
1033 // File listing spans multiple containers/shards
1034 list( , $shortCont, ) = self
::splitStoragePath( $params['dir'] );
1035 return new FileBackendStoreShardFileIterator( $this,
1036 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
1041 * Do not call this function from places outside FileBackend
1043 * @see FileBackendStore::getFileList()
1045 * @param string $container Resolved container name
1046 * @param string $dir Resolved path relative to container
1047 * @param array $params
1048 * @return Traversable|Array|null Returns null on failure
1050 abstract public function getFileListInternal( $container, $dir, array $params );
1053 * Return a list of FileOp objects from a list of operations.
1054 * Do not call this function from places outside FileBackend.
1056 * The result must have the same number of items as the input.
1057 * An exception is thrown if an unsupported operation is requested.
1059 * @param array $ops Same format as doOperations()
1060 * @return Array List of FileOp objects
1061 * @throws MWException
1063 final public function getOperationsInternal( array $ops ) {
1064 $supportedOps = array(
1065 'store' => 'StoreFileOp',
1066 'copy' => 'CopyFileOp',
1067 'move' => 'MoveFileOp',
1068 'delete' => 'DeleteFileOp',
1069 'create' => 'CreateFileOp',
1070 'describe' => 'DescribeFileOp',
1071 'null' => 'NullFileOp'
1074 $performOps = array(); // array of FileOp objects
1075 // Build up ordered array of FileOps...
1076 foreach ( $ops as $operation ) {
1077 $opName = $operation['op'];
1078 if ( isset( $supportedOps[$opName] ) ) {
1079 $class = $supportedOps[$opName];
1080 // Get params for this operation
1081 $params = $operation;
1082 // Append the FileOp class
1083 $performOps[] = new $class( $this, $params );
1085 throw new MWException( "Operation '$opName' is not supported." );
1093 * Get a list of storage paths to lock for a list of operations
1094 * Returns an array with 'sh' (shared) and 'ex' (exclusive) keys,
1095 * each corresponding to a list of storage paths to be locked.
1096 * All returned paths are normalized.
1098 * @param array $performOps List of FileOp objects
1099 * @return Array ('sh' => list of paths, 'ex' => list of paths)
1101 final public function getPathsToLockForOpsInternal( array $performOps ) {
1102 // Build up a list of files to lock...
1103 $paths = array( 'sh' => array(), 'ex' => array() );
1104 foreach ( $performOps as $fileOp ) {
1105 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1106 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1108 // Optimization: if doing an EX lock anyway, don't also set an SH one
1109 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1110 // Get a shared lock on the parent directory of each path changed
1111 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1117 * @see FileBackend::getScopedLocksForOps()
1120 public function getScopedLocksForOps( array $ops, Status
$status ) {
1121 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1123 $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status ),
1124 $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status )
1129 * @see FileBackend::doOperationsInternal()
1132 final protected function doOperationsInternal( array $ops, array $opts ) {
1133 wfProfileIn( __METHOD__
);
1134 wfProfileIn( __METHOD__
. '-' . $this->name
);
1135 $status = Status
::newGood();
1137 // Fix up custom header name/value pairs...
1138 $ops = array_map( array( $this, 'stripInvalidHeadersFromOp' ), $ops );
1140 // Build up a list of FileOps...
1141 $performOps = $this->getOperationsInternal( $ops );
1143 // Acquire any locks as needed...
1144 if ( empty( $opts['nonLocking'] ) ) {
1145 // Build up a list of files to lock...
1146 $paths = $this->getPathsToLockForOpsInternal( $performOps );
1147 // Try to lock those files for the scope of this function...
1148 $scopeLockS = $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status );
1149 $scopeLockE = $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status );
1150 if ( !$status->isOK() ) {
1151 wfProfileOut( __METHOD__
. '-' . $this->name
);
1152 wfProfileOut( __METHOD__
);
1153 return $status; // abort
1157 // Clear any file cache entries (after locks acquired)
1158 if ( empty( $opts['preserveCache'] ) ) {
1159 $this->clearCache();
1162 // Load from the persistent file and container caches
1163 $this->primeFileCache( $performOps );
1164 $this->primeContainerCache( $performOps );
1166 // Actually attempt the operation batch...
1167 $opts = $this->setConcurrencyFlags( $opts );
1168 $subStatus = FileOpBatch
::attempt( $performOps, $opts, $this->fileJournal
);
1170 // Merge errors into status fields
1171 $status->merge( $subStatus );
1172 $status->success
= $subStatus->success
; // not done in merge()
1174 wfProfileOut( __METHOD__
. '-' . $this->name
);
1175 wfProfileOut( __METHOD__
);
1180 * @see FileBackend::doQuickOperationsInternal()
1182 * @throws MWException
1184 final protected function doQuickOperationsInternal( array $ops ) {
1185 wfProfileIn( __METHOD__
);
1186 wfProfileIn( __METHOD__
. '-' . $this->name
);
1187 $status = Status
::newGood();
1189 // Fix up custom header name/value pairs...
1190 $ops = array_map( array( $this, 'stripInvalidHeadersFromOp' ), $ops );
1192 // Clear any file cache entries
1193 $this->clearCache();
1195 $supportedOps = array( 'create', 'store', 'copy', 'move', 'delete', 'null' );
1196 $async = ( $this->parallelize
=== 'implicit' && count( $ops ) > 1 );
1197 $maxConcurrency = $this->concurrency
; // throttle
1199 $statuses = array(); // array of (index => Status)
1200 $fileOpHandles = array(); // list of (index => handle) arrays
1201 $curFileOpHandles = array(); // current handle batch
1202 // Perform the sync-only ops and build up op handles for the async ops...
1203 foreach ( $ops as $index => $params ) {
1204 if ( !in_array( $params['op'], $supportedOps ) ) {
1205 wfProfileOut( __METHOD__
. '-' . $this->name
);
1206 wfProfileOut( __METHOD__
);
1207 throw new MWException( "Operation '{$params['op']}' is not supported." );
1209 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1210 $subStatus = $this->$method( array( 'async' => $async ) +
$params );
1211 if ( $subStatus->value
instanceof FileBackendStoreOpHandle
) { // async
1212 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1213 $fileOpHandles[] = $curFileOpHandles; // push this batch
1214 $curFileOpHandles = array();
1216 $curFileOpHandles[$index] = $subStatus->value
; // keep index
1217 } else { // error or completed
1218 $statuses[$index] = $subStatus; // keep index
1221 if ( count( $curFileOpHandles ) ) {
1222 $fileOpHandles[] = $curFileOpHandles; // last batch
1224 // Do all the async ops that can be done concurrently...
1225 foreach ( $fileOpHandles as $fileHandleBatch ) {
1226 $statuses = $statuses +
$this->executeOpHandlesInternal( $fileHandleBatch );
1228 // Marshall and merge all the responses...
1229 foreach ( $statuses as $index => $subStatus ) {
1230 $status->merge( $subStatus );
1231 if ( $subStatus->isOK() ) {
1232 $status->success
[$index] = true;
1233 ++
$status->successCount
;
1235 $status->success
[$index] = false;
1236 ++
$status->failCount
;
1240 wfProfileOut( __METHOD__
. '-' . $this->name
);
1241 wfProfileOut( __METHOD__
);
1246 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1247 * The resulting Status object fields will correspond
1248 * to the order in which the handles where given.
1250 * @param array $handles List of FileBackendStoreOpHandle objects
1251 * @return Array Map of Status objects
1252 * @throws MWException
1254 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1255 wfProfileIn( __METHOD__
);
1256 wfProfileIn( __METHOD__
. '-' . $this->name
);
1257 foreach ( $fileOpHandles as $fileOpHandle ) {
1258 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle
) ) {
1259 wfProfileOut( __METHOD__
. '-' . $this->name
);
1260 wfProfileOut( __METHOD__
);
1261 throw new MWException( "Given a non-FileBackendStoreOpHandle object." );
1262 } elseif ( $fileOpHandle->backend
->getName() !== $this->getName() ) {
1263 wfProfileOut( __METHOD__
. '-' . $this->name
);
1264 wfProfileOut( __METHOD__
);
1265 throw new MWException( "Given a FileBackendStoreOpHandle for the wrong backend." );
1268 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1269 foreach ( $fileOpHandles as $fileOpHandle ) {
1270 $fileOpHandle->closeResources();
1272 wfProfileOut( __METHOD__
. '-' . $this->name
);
1273 wfProfileOut( __METHOD__
);
1278 * @see FileBackendStore::executeOpHandlesInternal()
1279 * @param array $fileOpHandles
1280 * @throws MWException
1281 * @return Array List of corresponding Status objects
1283 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1284 foreach ( $fileOpHandles as $fileOpHandle ) { // OK if empty
1285 throw new MWException( "This backend supports no asynchronous operations." );
1291 * Strip long HTTP headers from a file operation.
1292 * Most headers are just numbers, but some are allowed to be long.
1293 * This function is useful for cleaning up headers and avoiding backend
1294 * specific errors, especially in the middle of batch file operations.
1296 * @param array $op Same format as doOperation()
1299 protected function stripInvalidHeadersFromOp( array $op ) {
1300 static $longs = array( 'Content-Disposition' );
1301 if ( isset( $op['headers'] ) ) { // op sets HTTP headers
1302 foreach ( $op['headers'] as $name => $value ) {
1303 $maxHVLen = in_array( $name, $longs ) ? INF
: 255;
1304 if ( strlen( $name ) > 255 ||
strlen( $value ) > $maxHVLen ) {
1305 trigger_error( "Header '$name: $value' is too long." );
1306 unset( $op['headers'][$name] );
1307 } elseif ( !strlen( $value ) ) {
1308 $op['headers'][$name] = ''; // null/false => ""
1316 * @see FileBackend::preloadCache()
1318 final public function preloadCache( array $paths ) {
1319 $fullConts = array(); // full container names
1320 foreach ( $paths as $path ) {
1321 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1322 $fullConts[] = $fullCont;
1324 // Load from the persistent file and container caches
1325 $this->primeContainerCache( $fullConts );
1326 $this->primeFileCache( $paths );
1330 * @see FileBackend::clearCache()
1332 final public function clearCache( array $paths = null ) {
1333 if ( is_array( $paths ) ) {
1334 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1335 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1337 if ( $paths === null ) {
1338 $this->cheapCache
->clear();
1339 $this->expensiveCache
->clear();
1341 foreach ( $paths as $path ) {
1342 $this->cheapCache
->clear( $path );
1343 $this->expensiveCache
->clear( $path );
1346 $this->doClearCache( $paths );
1350 * Clears any additional stat caches for storage paths
1352 * @see FileBackend::clearCache()
1354 * @param array $paths Storage paths (optional)
1357 protected function doClearCache( array $paths = null ) {}
1360 * Is this a key/value store where directories are just virtual?
1361 * Virtual directories exists in so much as files exists that are
1362 * prefixed with the directory path followed by a forward slash.
1366 abstract protected function directoriesAreVirtual();
1369 * Check if a container name is valid.
1370 * This checks for for length and illegal characters.
1372 * @param $container string
1375 final protected static function isValidContainerName( $container ) {
1376 // This accounts for Swift and S3 restrictions while leaving room
1377 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1378 // This disallows directory separators or traversal characters.
1379 // Note that matching strings URL encode to the same string;
1380 // in Swift, the length restriction is *after* URL encoding.
1381 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1385 * Splits a storage path into an internal container name,
1386 * an internal relative file name, and a container shard suffix.
1387 * Any shard suffix is already appended to the internal container name.
1388 * This also checks that the storage path is valid and within this backend.
1390 * If the container is sharded but a suffix could not be determined,
1391 * this means that the path can only refer to a directory and can only
1392 * be scanned by looking in all the container shards.
1394 * @param $storagePath string
1395 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1397 final protected function resolveStoragePath( $storagePath ) {
1398 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1399 if ( $backend === $this->name
) { // must be for this backend
1400 $relPath = self
::normalizeContainerPath( $relPath );
1401 if ( $relPath !== null ) {
1402 // Get shard for the normalized path if this container is sharded
1403 $cShard = $this->getContainerShard( $container, $relPath );
1404 // Validate and sanitize the relative path (backend-specific)
1405 $relPath = $this->resolveContainerPath( $container, $relPath );
1406 if ( $relPath !== null ) {
1407 // Prepend any wiki ID prefix to the container name
1408 $container = $this->fullContainerName( $container );
1409 if ( self
::isValidContainerName( $container ) ) {
1410 // Validate and sanitize the container name (backend-specific)
1411 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1412 if ( $container !== null ) {
1413 return array( $container, $relPath, $cShard );
1419 return array( null, null, null );
1423 * Like resolveStoragePath() except null values are returned if
1424 * the container is sharded and the shard could not be determined
1425 * or if the path ends with '/'. The later case is illegal for FS
1426 * backends and can confuse listings for object store backends.
1428 * This function is used when resolving paths that must be valid
1429 * locations for files. Directory and listing functions should
1430 * generally just use resolveStoragePath() instead.
1432 * @see FileBackendStore::resolveStoragePath()
1434 * @param $storagePath string
1435 * @return Array (container, path) or (null, null) if invalid
1437 final protected function resolveStoragePathReal( $storagePath ) {
1438 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1439 if ( $cShard !== null && substr( $relPath, -1 ) !== '/' ) {
1440 return array( $container, $relPath );
1442 return array( null, null );
1446 * Get the container name shard suffix for a given path.
1447 * Any empty suffix means the container is not sharded.
1449 * @param string $container Container name
1450 * @param string $relPath Storage path relative to the container
1451 * @return string|null Returns null if shard could not be determined
1453 final protected function getContainerShard( $container, $relPath ) {
1454 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1455 if ( $levels == 1 ||
$levels == 2 ) {
1456 // Hash characters are either base 16 or 36
1457 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1458 // Get a regex that represents the shard portion of paths.
1459 // The concatenation of the captures gives us the shard.
1460 if ( $levels === 1 ) { // 16 or 36 shards per container
1461 $hashDirRegex = '(' . $char . ')';
1462 } else { // 256 or 1296 shards per container
1463 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1464 $hashDirRegex = $char . '/(' . $char . '{2})';
1465 } else { // short hash dir format (e.g. "a/b/c")
1466 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1469 // Allow certain directories to be above the hash dirs so as
1470 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1471 // They must be 2+ chars to avoid any hash directory ambiguity.
1473 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1474 return '.' . implode( '', array_slice( $m, 1 ) );
1476 return null; // failed to match
1478 return ''; // no sharding
1482 * Check if a storage path maps to a single shard.
1483 * Container dirs like "a", where the container shards on "x/xy",
1484 * can reside on several shards. Such paths are tricky to handle.
1486 * @param string $storagePath Storage path
1489 final public function isSingleShardPathInternal( $storagePath ) {
1490 list( , , $shard ) = $this->resolveStoragePath( $storagePath );
1491 return ( $shard !== null );
1495 * Get the sharding config for a container.
1496 * If greater than 0, then all file storage paths within
1497 * the container are required to be hashed accordingly.
1499 * @param $container string
1500 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
1502 final protected function getContainerHashLevels( $container ) {
1503 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1504 $config = $this->shardViaHashLevels
[$container];
1505 $hashLevels = (int)$config['levels'];
1506 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1507 $hashBase = (int)$config['base'];
1508 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1509 return array( $hashLevels, $hashBase, $config['repeat'] );
1513 return array( 0, 0, false ); // no sharding
1517 * Get a list of full container shard suffixes for a container
1519 * @param $container string
1522 final protected function getContainerSuffixes( $container ) {
1524 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1525 if ( $digits > 0 ) {
1526 $numShards = pow( $base, $digits );
1527 for ( $index = 0; $index < $numShards; $index++
) {
1528 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1535 * Get the full container name, including the wiki ID prefix
1537 * @param $container string
1540 final protected function fullContainerName( $container ) {
1541 if ( $this->wikiId
!= '' ) {
1542 return "{$this->wikiId}-$container";
1549 * Resolve a container name, checking if it's allowed by the backend.
1550 * This is intended for internal use, such as encoding illegal chars.
1551 * Subclasses can override this to be more restrictive.
1553 * @param $container string
1554 * @return string|null
1556 protected function resolveContainerName( $container ) {
1561 * Resolve a relative storage path, checking if it's allowed by the backend.
1562 * This is intended for internal use, such as encoding illegal chars or perhaps
1563 * getting absolute paths (e.g. FS based backends). Note that the relative path
1564 * may be the empty string (e.g. the path is simply to the container).
1566 * @param string $container Container name
1567 * @param string $relStoragePath Storage path relative to the container
1568 * @return string|null Path or null if not valid
1570 protected function resolveContainerPath( $container, $relStoragePath ) {
1571 return $relStoragePath;
1575 * Get the cache key for a container
1577 * @param string $container Resolved container name
1580 private function containerCacheKey( $container ) {
1581 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1585 * Set the cached info for a container
1587 * @param string $container Resolved container name
1588 * @param array $val Information to cache
1591 final protected function setContainerCache( $container, array $val ) {
1592 $this->memCache
->add( $this->containerCacheKey( $container ), $val, 14 * 86400 );
1596 * Delete the cached info for a container.
1597 * The cache key is salted for a while to prevent race conditions.
1599 * @param string $container Resolved container name
1602 final protected function deleteContainerCache( $container ) {
1603 if ( !$this->memCache
->set( $this->containerCacheKey( $container ), 'PURGED', 300 ) ) {
1604 trigger_error( "Unable to delete stat cache for container $container." );
1609 * Do a batch lookup from cache for container stats for all containers
1610 * used in a list of container names, storage paths, or FileOp objects.
1611 * This loads the persistent cache values into the process cache.
1613 * @param $items Array
1616 final protected function primeContainerCache( array $items ) {
1617 wfProfileIn( __METHOD__
);
1618 wfProfileIn( __METHOD__
. '-' . $this->name
);
1620 $paths = array(); // list of storage paths
1621 $contNames = array(); // (cache key => resolved container name)
1622 // Get all the paths/containers from the items...
1623 foreach ( $items as $item ) {
1624 if ( $item instanceof FileOp
) {
1625 $paths = array_merge( $paths, $item->storagePathsRead() );
1626 $paths = array_merge( $paths, $item->storagePathsChanged() );
1627 } elseif ( self
::isStoragePath( $item ) ) {
1629 } elseif ( is_string( $item ) ) { // full container name
1630 $contNames[$this->containerCacheKey( $item )] = $item;
1633 // Get all the corresponding cache keys for paths...
1634 foreach ( $paths as $path ) {
1635 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1636 if ( $fullCont !== null ) { // valid path for this backend
1637 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1641 $contInfo = array(); // (resolved container name => cache value)
1642 // Get all cache entries for these container cache keys...
1643 $values = $this->memCache
->getMulti( array_keys( $contNames ) );
1644 foreach ( $values as $cacheKey => $val ) {
1645 $contInfo[$contNames[$cacheKey]] = $val;
1648 // Populate the container process cache for the backend...
1649 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1651 wfProfileOut( __METHOD__
. '-' . $this->name
);
1652 wfProfileOut( __METHOD__
);
1656 * Fill the backend-specific process cache given an array of
1657 * resolved container names and their corresponding cached info.
1658 * Only containers that actually exist should appear in the map.
1660 * @param array $containerInfo Map of resolved container names to cached info
1663 protected function doPrimeContainerCache( array $containerInfo ) {}
1666 * Get the cache key for a file path
1668 * @param string $path Normalized storage path
1671 private function fileCacheKey( $path ) {
1672 return wfMemcKey( 'backend', $this->getName(), 'file', sha1( $path ) );
1676 * Set the cached stat info for a file path.
1677 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1678 * salting for the case when a file is created at a path were there was none before.
1680 * @param string $path Storage path
1681 * @param array $val Stat information to cache
1684 final protected function setFileCache( $path, array $val ) {
1685 $path = FileBackend
::normalizeStoragePath( $path );
1686 if ( $path === null ) {
1687 return; // invalid storage path
1689 $age = time() - wfTimestamp( TS_UNIX
, $val['mtime'] );
1690 $ttl = min( 7 * 86400, max( 300, floor( .1 * $age ) ) );
1691 $this->memCache
->add( $this->fileCacheKey( $path ), $val, $ttl );
1695 * Delete the cached stat info for a file path.
1696 * The cache key is salted for a while to prevent race conditions.
1697 * Since negatives (404s) are not cached, this does not need to be called when
1698 * a file is created at a path were there was none before.
1700 * @param string $path Storage path
1703 final protected function deleteFileCache( $path ) {
1704 $path = FileBackend
::normalizeStoragePath( $path );
1705 if ( $path === null ) {
1706 return; // invalid storage path
1708 if ( !$this->memCache
->set( $this->fileCacheKey( $path ), 'PURGED', 300 ) ) {
1709 trigger_error( "Unable to delete stat cache for file $path." );
1714 * Do a batch lookup from cache for file stats for all paths
1715 * used in a list of storage paths or FileOp objects.
1716 * This loads the persistent cache values into the process cache.
1718 * @param array $items List of storage paths or FileOps
1721 final protected function primeFileCache( array $items ) {
1722 wfProfileIn( __METHOD__
);
1723 wfProfileIn( __METHOD__
. '-' . $this->name
);
1725 $paths = array(); // list of storage paths
1726 $pathNames = array(); // (cache key => storage path)
1727 // Get all the paths/containers from the items...
1728 foreach ( $items as $item ) {
1729 if ( $item instanceof FileOp
) {
1730 $paths = array_merge( $paths, $item->storagePathsRead() );
1731 $paths = array_merge( $paths, $item->storagePathsChanged() );
1732 } elseif ( self
::isStoragePath( $item ) ) {
1733 $paths[] = FileBackend
::normalizeStoragePath( $item );
1736 // Get rid of any paths that failed normalization...
1737 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1738 // Get all the corresponding cache keys for paths...
1739 foreach ( $paths as $path ) {
1740 list( , $rel, ) = $this->resolveStoragePath( $path );
1741 if ( $rel !== null ) { // valid path for this backend
1742 $pathNames[$this->fileCacheKey( $path )] = $path;
1745 // Get all cache entries for these container cache keys...
1746 $values = $this->memCache
->getMulti( array_keys( $pathNames ) );
1747 foreach ( $values as $cacheKey => $val ) {
1748 if ( is_array( $val ) ) {
1749 $path = $pathNames[$cacheKey];
1750 $this->cheapCache
->set( $path, 'stat', $val );
1751 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1752 $this->cheapCache
->set( $path, 'sha1',
1753 array( 'hash' => $val['sha1'], 'latest' => $val['latest'] ) );
1758 wfProfileOut( __METHOD__
. '-' . $this->name
);
1759 wfProfileOut( __METHOD__
);
1763 * Set the 'concurrency' option from a list of operation options
1765 * @param array $opts Map of operation options
1768 final protected function setConcurrencyFlags( array $opts ) {
1769 $opts['concurrency'] = 1; // off
1770 if ( $this->parallelize
=== 'implicit' ) {
1771 if ( !isset( $opts['parallelize'] ) ||
$opts['parallelize'] ) {
1772 $opts['concurrency'] = $this->concurrency
;
1774 } elseif ( $this->parallelize
=== 'explicit' ) {
1775 if ( !empty( $opts['parallelize'] ) ) {
1776 $opts['concurrency'] = $this->concurrency
;
1784 * FileBackendStore helper class for performing asynchronous file operations.
1786 * For example, calling FileBackendStore::createInternal() with the "async"
1787 * param flag may result in a Status that contains this object as a value.
1788 * This class is largely backend-specific and is mostly just "magic" to be
1789 * passed to FileBackendStore::executeOpHandlesInternal().
1791 abstract class FileBackendStoreOpHandle
{
1793 public $params = array(); // params to caller functions
1794 /** @var FileBackendStore */
1797 public $resourcesToClose = array();
1799 public $call; // string; name that identifies the function called
1802 * Close all open file handles
1806 public function closeResources() {
1807 array_map( 'fclose', $this->resourcesToClose
);
1812 * FileBackendStore helper function to handle listings that span container shards.
1813 * Do not use this class from places outside of FileBackendStore.
1815 * @ingroup FileBackend
1817 abstract class FileBackendStoreShardListIterator
extends FilterIterator
{
1818 /** @var FileBackendStore */
1823 protected $container; // string; full container name
1824 protected $directory; // string; resolved relative path
1827 protected $multiShardPaths = array(); // (rel path => 1)
1830 * @param $backend FileBackendStore
1831 * @param string $container Full storage container name
1832 * @param string $dir Storage directory relative to container
1833 * @param array $suffixes List of container shard suffixes
1834 * @param array $params
1836 public function __construct(
1837 FileBackendStore
$backend, $container, $dir, array $suffixes, array $params
1839 $this->backend
= $backend;
1840 $this->container
= $container;
1841 $this->directory
= $dir;
1842 $this->params
= $params;
1844 $iter = new AppendIterator();
1845 foreach ( $suffixes as $suffix ) {
1846 $iter->append( $this->listFromShard( $this->container
. $suffix ) );
1849 parent
::__construct( $iter );
1852 public function accept() {
1853 $rel = $this->getInnerIterator()->current(); // path relative to given directory
1854 $path = $this->params
['dir'] . "/{$rel}"; // full storage path
1855 if ( $this->backend
->isSingleShardPathInternal( $path ) ) {
1856 return true; // path is only on one shard; no issue with duplicates
1857 } elseif ( isset( $this->multiShardPaths
[$rel] ) ) {
1858 // Don't keep listing paths that are on multiple shards
1861 $this->multiShardPaths
[$rel] = 1;
1866 public function rewind() {
1868 $this->multiShardPaths
= array();
1872 * Get the list for a given container shard
1874 * @param string $container Resolved container name
1877 abstract protected function listFromShard( $container );
1881 * Iterator for listing directories
1883 class FileBackendStoreShardDirIterator
extends FileBackendStoreShardListIterator
{
1884 protected function listFromShard( $container ) {
1885 $list = $this->backend
->getDirectoryListInternal(
1886 $container, $this->directory
, $this->params
);
1887 if ( $list === null ) {
1888 return new ArrayIterator( array() );
1890 return is_array( $list ) ?
new ArrayIterator( $list ) : $list;
1896 * Iterator for listing regular files
1898 class FileBackendStoreShardFileIterator
extends FileBackendStoreShardListIterator
{
1899 protected function listFromShard( $container ) {
1900 $list = $this->backend
->getFileListInternal(
1901 $container, $this->directory
, $this->params
);
1902 if ( $list === null ) {
1903 return new ArrayIterator( array() );
1905 return is_array( $list ) ?
new ArrayIterator( $list ) : $list;