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 if ( !count( $ops ) ) {
1138 return $status; // nothing to do
1141 // Fix up custom header name/value pairs...
1142 $ops = array_map( array( $this, 'stripInvalidHeadersFromOp' ), $ops );
1144 // Build up a list of FileOps...
1145 $performOps = $this->getOperationsInternal( $ops );
1147 // Acquire any locks as needed...
1148 if ( empty( $opts['nonLocking'] ) ) {
1149 // Build up a list of files to lock...
1150 $paths = $this->getPathsToLockForOpsInternal( $performOps );
1151 // Try to lock those files for the scope of this function...
1152 $scopeLockS = $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status );
1153 $scopeLockE = $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status );
1154 if ( !$status->isOK() ) {
1155 wfProfileOut( __METHOD__
. '-' . $this->name
);
1156 wfProfileOut( __METHOD__
);
1157 return $status; // abort
1161 // Clear any file cache entries (after locks acquired)
1162 if ( empty( $opts['preserveCache'] ) ) {
1163 $this->clearCache();
1166 // Load from the persistent file and container caches
1167 $this->primeFileCache( $performOps );
1168 $this->primeContainerCache( $performOps );
1170 // Actually attempt the operation batch...
1171 $opts = $this->setConcurrencyFlags( $opts );
1172 $subStatus = FileOpBatch
::attempt( $performOps, $opts, $this->fileJournal
);
1174 // Merge errors into status fields
1175 $status->merge( $subStatus );
1176 $status->success
= $subStatus->success
; // not done in merge()
1178 wfProfileOut( __METHOD__
. '-' . $this->name
);
1179 wfProfileOut( __METHOD__
);
1184 * @see FileBackend::doQuickOperationsInternal()
1186 * @throws MWException
1188 final protected function doQuickOperationsInternal( array $ops ) {
1189 wfProfileIn( __METHOD__
);
1190 wfProfileIn( __METHOD__
. '-' . $this->name
);
1191 $status = Status
::newGood();
1193 if ( !count( $ops ) ) {
1194 return $status; // nothing to do
1197 // Fix up custom header name/value pairs...
1198 $ops = array_map( array( $this, 'stripInvalidHeadersFromOp' ), $ops );
1200 // Clear any file cache entries
1201 $this->clearCache();
1203 $supportedOps = array( 'create', 'store', 'copy', 'move', 'delete', 'null' );
1204 $async = ( $this->parallelize
=== 'implicit' );
1205 $maxConcurrency = $this->concurrency
; // throttle
1207 $statuses = array(); // array of (index => Status)
1208 $fileOpHandles = array(); // list of (index => handle) arrays
1209 $curFileOpHandles = array(); // current handle batch
1210 // Perform the sync-only ops and build up op handles for the async ops...
1211 foreach ( $ops as $index => $params ) {
1212 if ( !in_array( $params['op'], $supportedOps ) ) {
1213 wfProfileOut( __METHOD__
. '-' . $this->name
);
1214 wfProfileOut( __METHOD__
);
1215 throw new MWException( "Operation '{$params['op']}' is not supported." );
1217 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1218 $subStatus = $this->$method( array( 'async' => $async ) +
$params );
1219 if ( $subStatus->value
instanceof FileBackendStoreOpHandle
) { // async
1220 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1221 $fileOpHandles[] = $curFileOpHandles; // push this batch
1222 $curFileOpHandles = array();
1224 $curFileOpHandles[$index] = $subStatus->value
; // keep index
1225 } else { // error or completed
1226 $statuses[$index] = $subStatus; // keep index
1229 if ( count( $curFileOpHandles ) ) {
1230 $fileOpHandles[] = $curFileOpHandles; // last batch
1232 // Do all the async ops that can be done concurrently...
1233 foreach ( $fileOpHandles as $fileHandleBatch ) {
1234 $statuses = $statuses +
$this->executeOpHandlesInternal( $fileHandleBatch );
1236 // Marshall and merge all the responses...
1237 foreach ( $statuses as $index => $subStatus ) {
1238 $status->merge( $subStatus );
1239 if ( $subStatus->isOK() ) {
1240 $status->success
[$index] = true;
1241 ++
$status->successCount
;
1243 $status->success
[$index] = false;
1244 ++
$status->failCount
;
1248 wfProfileOut( __METHOD__
. '-' . $this->name
);
1249 wfProfileOut( __METHOD__
);
1254 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1255 * The resulting Status object fields will correspond
1256 * to the order in which the handles where given.
1258 * @param array $handles List of FileBackendStoreOpHandle objects
1259 * @return Array Map of Status objects
1260 * @throws MWException
1262 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1263 wfProfileIn( __METHOD__
);
1264 wfProfileIn( __METHOD__
. '-' . $this->name
);
1265 foreach ( $fileOpHandles as $fileOpHandle ) {
1266 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle
) ) {
1267 wfProfileOut( __METHOD__
. '-' . $this->name
);
1268 wfProfileOut( __METHOD__
);
1269 throw new MWException( "Given a non-FileBackendStoreOpHandle object." );
1270 } elseif ( $fileOpHandle->backend
->getName() !== $this->getName() ) {
1271 wfProfileOut( __METHOD__
. '-' . $this->name
);
1272 wfProfileOut( __METHOD__
);
1273 throw new MWException( "Given a FileBackendStoreOpHandle for the wrong backend." );
1276 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1277 foreach ( $fileOpHandles as $fileOpHandle ) {
1278 $fileOpHandle->closeResources();
1280 wfProfileOut( __METHOD__
. '-' . $this->name
);
1281 wfProfileOut( __METHOD__
);
1286 * @see FileBackendStore::executeOpHandlesInternal()
1287 * @param array $fileOpHandles
1288 * @throws MWException
1289 * @return Array List of corresponding Status objects
1291 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1292 foreach ( $fileOpHandles as $fileOpHandle ) { // OK if empty
1293 throw new MWException( "This backend supports no asynchronous operations." );
1299 * Strip long HTTP headers from a file operation.
1300 * Most headers are just numbers, but some are allowed to be long.
1301 * This function is useful for cleaning up headers and avoiding backend
1302 * specific errors, especially in the middle of batch file operations.
1304 * @param array $op Same format as doOperation()
1307 protected function stripInvalidHeadersFromOp( array $op ) {
1308 static $longs = array( 'Content-Disposition' );
1309 if ( isset( $op['headers'] ) ) { // op sets HTTP headers
1310 foreach ( $op['headers'] as $name => $value ) {
1311 $maxHVLen = in_array( $name, $longs ) ? INF
: 255;
1312 if ( strlen( $name ) > 255 ||
strlen( $value ) > $maxHVLen ) {
1313 trigger_error( "Header '$name: $value' is too long." );
1314 unset( $op['headers'][$name] );
1315 } elseif ( !strlen( $value ) ) {
1316 $op['headers'][$name] = ''; // null/false => ""
1324 * @see FileBackend::preloadCache()
1326 final public function preloadCache( array $paths ) {
1327 $fullConts = array(); // full container names
1328 foreach ( $paths as $path ) {
1329 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1330 $fullConts[] = $fullCont;
1332 // Load from the persistent file and container caches
1333 $this->primeContainerCache( $fullConts );
1334 $this->primeFileCache( $paths );
1338 * @see FileBackend::clearCache()
1340 final public function clearCache( array $paths = null ) {
1341 if ( is_array( $paths ) ) {
1342 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1343 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1345 if ( $paths === null ) {
1346 $this->cheapCache
->clear();
1347 $this->expensiveCache
->clear();
1349 foreach ( $paths as $path ) {
1350 $this->cheapCache
->clear( $path );
1351 $this->expensiveCache
->clear( $path );
1354 $this->doClearCache( $paths );
1358 * Clears any additional stat caches for storage paths
1360 * @see FileBackend::clearCache()
1362 * @param array $paths Storage paths (optional)
1365 protected function doClearCache( array $paths = null ) {}
1368 * Is this a key/value store where directories are just virtual?
1369 * Virtual directories exists in so much as files exists that are
1370 * prefixed with the directory path followed by a forward slash.
1374 abstract protected function directoriesAreVirtual();
1377 * Check if a container name is valid.
1378 * This checks for for length and illegal characters.
1380 * @param $container string
1383 final protected static function isValidContainerName( $container ) {
1384 // This accounts for Swift and S3 restrictions while leaving room
1385 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1386 // This disallows directory separators or traversal characters.
1387 // Note that matching strings URL encode to the same string;
1388 // in Swift, the length restriction is *after* URL encoding.
1389 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1393 * Splits a storage path into an internal container name,
1394 * an internal relative file name, and a container shard suffix.
1395 * Any shard suffix is already appended to the internal container name.
1396 * This also checks that the storage path is valid and within this backend.
1398 * If the container is sharded but a suffix could not be determined,
1399 * this means that the path can only refer to a directory and can only
1400 * be scanned by looking in all the container shards.
1402 * @param $storagePath string
1403 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1405 final protected function resolveStoragePath( $storagePath ) {
1406 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1407 if ( $backend === $this->name
) { // must be for this backend
1408 $relPath = self
::normalizeContainerPath( $relPath );
1409 if ( $relPath !== null ) {
1410 // Get shard for the normalized path if this container is sharded
1411 $cShard = $this->getContainerShard( $container, $relPath );
1412 // Validate and sanitize the relative path (backend-specific)
1413 $relPath = $this->resolveContainerPath( $container, $relPath );
1414 if ( $relPath !== null ) {
1415 // Prepend any wiki ID prefix to the container name
1416 $container = $this->fullContainerName( $container );
1417 if ( self
::isValidContainerName( $container ) ) {
1418 // Validate and sanitize the container name (backend-specific)
1419 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1420 if ( $container !== null ) {
1421 return array( $container, $relPath, $cShard );
1427 return array( null, null, null );
1431 * Like resolveStoragePath() except null values are returned if
1432 * the container is sharded and the shard could not be determined
1433 * or if the path ends with '/'. The later case is illegal for FS
1434 * backends and can confuse listings for object store backends.
1436 * This function is used when resolving paths that must be valid
1437 * locations for files. Directory and listing functions should
1438 * generally just use resolveStoragePath() instead.
1440 * @see FileBackendStore::resolveStoragePath()
1442 * @param $storagePath string
1443 * @return Array (container, path) or (null, null) if invalid
1445 final protected function resolveStoragePathReal( $storagePath ) {
1446 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1447 if ( $cShard !== null && substr( $relPath, -1 ) !== '/' ) {
1448 return array( $container, $relPath );
1450 return array( null, null );
1454 * Get the container name shard suffix for a given path.
1455 * Any empty suffix means the container is not sharded.
1457 * @param string $container Container name
1458 * @param string $relPath Storage path relative to the container
1459 * @return string|null Returns null if shard could not be determined
1461 final protected function getContainerShard( $container, $relPath ) {
1462 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1463 if ( $levels == 1 ||
$levels == 2 ) {
1464 // Hash characters are either base 16 or 36
1465 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1466 // Get a regex that represents the shard portion of paths.
1467 // The concatenation of the captures gives us the shard.
1468 if ( $levels === 1 ) { // 16 or 36 shards per container
1469 $hashDirRegex = '(' . $char . ')';
1470 } else { // 256 or 1296 shards per container
1471 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1472 $hashDirRegex = $char . '/(' . $char . '{2})';
1473 } else { // short hash dir format (e.g. "a/b/c")
1474 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1477 // Allow certain directories to be above the hash dirs so as
1478 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1479 // They must be 2+ chars to avoid any hash directory ambiguity.
1481 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1482 return '.' . implode( '', array_slice( $m, 1 ) );
1484 return null; // failed to match
1486 return ''; // no sharding
1490 * Check if a storage path maps to a single shard.
1491 * Container dirs like "a", where the container shards on "x/xy",
1492 * can reside on several shards. Such paths are tricky to handle.
1494 * @param string $storagePath Storage path
1497 final public function isSingleShardPathInternal( $storagePath ) {
1498 list( , , $shard ) = $this->resolveStoragePath( $storagePath );
1499 return ( $shard !== null );
1503 * Get the sharding config for a container.
1504 * If greater than 0, then all file storage paths within
1505 * the container are required to be hashed accordingly.
1507 * @param $container string
1508 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
1510 final protected function getContainerHashLevels( $container ) {
1511 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1512 $config = $this->shardViaHashLevels
[$container];
1513 $hashLevels = (int)$config['levels'];
1514 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1515 $hashBase = (int)$config['base'];
1516 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1517 return array( $hashLevels, $hashBase, $config['repeat'] );
1521 return array( 0, 0, false ); // no sharding
1525 * Get a list of full container shard suffixes for a container
1527 * @param $container string
1530 final protected function getContainerSuffixes( $container ) {
1532 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1533 if ( $digits > 0 ) {
1534 $numShards = pow( $base, $digits );
1535 for ( $index = 0; $index < $numShards; $index++
) {
1536 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1543 * Get the full container name, including the wiki ID prefix
1545 * @param $container string
1548 final protected function fullContainerName( $container ) {
1549 if ( $this->wikiId
!= '' ) {
1550 return "{$this->wikiId}-$container";
1557 * Resolve a container name, checking if it's allowed by the backend.
1558 * This is intended for internal use, such as encoding illegal chars.
1559 * Subclasses can override this to be more restrictive.
1561 * @param $container string
1562 * @return string|null
1564 protected function resolveContainerName( $container ) {
1569 * Resolve a relative storage path, checking if it's allowed by the backend.
1570 * This is intended for internal use, such as encoding illegal chars or perhaps
1571 * getting absolute paths (e.g. FS based backends). Note that the relative path
1572 * may be the empty string (e.g. the path is simply to the container).
1574 * @param string $container Container name
1575 * @param string $relStoragePath Storage path relative to the container
1576 * @return string|null Path or null if not valid
1578 protected function resolveContainerPath( $container, $relStoragePath ) {
1579 return $relStoragePath;
1583 * Get the cache key for a container
1585 * @param string $container Resolved container name
1588 private function containerCacheKey( $container ) {
1589 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1593 * Set the cached info for a container
1595 * @param string $container Resolved container name
1596 * @param array $val Information to cache
1599 final protected function setContainerCache( $container, array $val ) {
1600 $this->memCache
->add( $this->containerCacheKey( $container ), $val, 14 * 86400 );
1604 * Delete the cached info for a container.
1605 * The cache key is salted for a while to prevent race conditions.
1607 * @param string $container Resolved container name
1610 final protected function deleteContainerCache( $container ) {
1611 if ( !$this->memCache
->set( $this->containerCacheKey( $container ), 'PURGED', 300 ) ) {
1612 trigger_error( "Unable to delete stat cache for container $container." );
1617 * Do a batch lookup from cache for container stats for all containers
1618 * used in a list of container names, storage paths, or FileOp objects.
1619 * This loads the persistent cache values into the process cache.
1621 * @param $items Array
1624 final protected function primeContainerCache( array $items ) {
1625 wfProfileIn( __METHOD__
);
1626 wfProfileIn( __METHOD__
. '-' . $this->name
);
1628 $paths = array(); // list of storage paths
1629 $contNames = array(); // (cache key => resolved container name)
1630 // Get all the paths/containers from the items...
1631 foreach ( $items as $item ) {
1632 if ( $item instanceof FileOp
) {
1633 $paths = array_merge( $paths, $item->storagePathsRead() );
1634 $paths = array_merge( $paths, $item->storagePathsChanged() );
1635 } elseif ( self
::isStoragePath( $item ) ) {
1637 } elseif ( is_string( $item ) ) { // full container name
1638 $contNames[$this->containerCacheKey( $item )] = $item;
1641 // Get all the corresponding cache keys for paths...
1642 foreach ( $paths as $path ) {
1643 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1644 if ( $fullCont !== null ) { // valid path for this backend
1645 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1649 $contInfo = array(); // (resolved container name => cache value)
1650 // Get all cache entries for these container cache keys...
1651 $values = $this->memCache
->getMulti( array_keys( $contNames ) );
1652 foreach ( $values as $cacheKey => $val ) {
1653 $contInfo[$contNames[$cacheKey]] = $val;
1656 // Populate the container process cache for the backend...
1657 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1659 wfProfileOut( __METHOD__
. '-' . $this->name
);
1660 wfProfileOut( __METHOD__
);
1664 * Fill the backend-specific process cache given an array of
1665 * resolved container names and their corresponding cached info.
1666 * Only containers that actually exist should appear in the map.
1668 * @param array $containerInfo Map of resolved container names to cached info
1671 protected function doPrimeContainerCache( array $containerInfo ) {}
1674 * Get the cache key for a file path
1676 * @param string $path Normalized storage path
1679 private function fileCacheKey( $path ) {
1680 return wfMemcKey( 'backend', $this->getName(), 'file', sha1( $path ) );
1684 * Set the cached stat info for a file path.
1685 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1686 * salting for the case when a file is created at a path were there was none before.
1688 * @param string $path Storage path
1689 * @param array $val Stat information to cache
1692 final protected function setFileCache( $path, array $val ) {
1693 $path = FileBackend
::normalizeStoragePath( $path );
1694 if ( $path === null ) {
1695 return; // invalid storage path
1697 $age = time() - wfTimestamp( TS_UNIX
, $val['mtime'] );
1698 $ttl = min( 7 * 86400, max( 300, floor( .1 * $age ) ) );
1699 $this->memCache
->add( $this->fileCacheKey( $path ), $val, $ttl );
1703 * Delete the cached stat info for a file path.
1704 * The cache key is salted for a while to prevent race conditions.
1705 * Since negatives (404s) are not cached, this does not need to be called when
1706 * a file is created at a path were there was none before.
1708 * @param string $path Storage path
1711 final protected function deleteFileCache( $path ) {
1712 $path = FileBackend
::normalizeStoragePath( $path );
1713 if ( $path === null ) {
1714 return; // invalid storage path
1716 if ( !$this->memCache
->set( $this->fileCacheKey( $path ), 'PURGED', 300 ) ) {
1717 trigger_error( "Unable to delete stat cache for file $path." );
1722 * Do a batch lookup from cache for file stats for all paths
1723 * used in a list of storage paths or FileOp objects.
1724 * This loads the persistent cache values into the process cache.
1726 * @param array $items List of storage paths or FileOps
1729 final protected function primeFileCache( array $items ) {
1730 wfProfileIn( __METHOD__
);
1731 wfProfileIn( __METHOD__
. '-' . $this->name
);
1733 $paths = array(); // list of storage paths
1734 $pathNames = array(); // (cache key => storage path)
1735 // Get all the paths/containers from the items...
1736 foreach ( $items as $item ) {
1737 if ( $item instanceof FileOp
) {
1738 $paths = array_merge( $paths, $item->storagePathsRead() );
1739 $paths = array_merge( $paths, $item->storagePathsChanged() );
1740 } elseif ( self
::isStoragePath( $item ) ) {
1741 $paths[] = FileBackend
::normalizeStoragePath( $item );
1744 // Get rid of any paths that failed normalization...
1745 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1746 // Get all the corresponding cache keys for paths...
1747 foreach ( $paths as $path ) {
1748 list( , $rel, ) = $this->resolveStoragePath( $path );
1749 if ( $rel !== null ) { // valid path for this backend
1750 $pathNames[$this->fileCacheKey( $path )] = $path;
1753 // Get all cache entries for these container cache keys...
1754 $values = $this->memCache
->getMulti( array_keys( $pathNames ) );
1755 foreach ( $values as $cacheKey => $val ) {
1756 if ( is_array( $val ) ) {
1757 $path = $pathNames[$cacheKey];
1758 $this->cheapCache
->set( $path, 'stat', $val );
1759 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1760 $this->cheapCache
->set( $path, 'sha1',
1761 array( 'hash' => $val['sha1'], 'latest' => $val['latest'] ) );
1766 wfProfileOut( __METHOD__
. '-' . $this->name
);
1767 wfProfileOut( __METHOD__
);
1771 * Set the 'concurrency' option from a list of operation options
1773 * @param array $opts Map of operation options
1776 final protected function setConcurrencyFlags( array $opts ) {
1777 $opts['concurrency'] = 1; // off
1778 if ( $this->parallelize
=== 'implicit' ) {
1779 if ( !isset( $opts['parallelize'] ) ||
$opts['parallelize'] ) {
1780 $opts['concurrency'] = $this->concurrency
;
1782 } elseif ( $this->parallelize
=== 'explicit' ) {
1783 if ( !empty( $opts['parallelize'] ) ) {
1784 $opts['concurrency'] = $this->concurrency
;
1792 * FileBackendStore helper class for performing asynchronous file operations.
1794 * For example, calling FileBackendStore::createInternal() with the "async"
1795 * param flag may result in a Status that contains this object as a value.
1796 * This class is largely backend-specific and is mostly just "magic" to be
1797 * passed to FileBackendStore::executeOpHandlesInternal().
1799 abstract class FileBackendStoreOpHandle
{
1801 public $params = array(); // params to caller functions
1802 /** @var FileBackendStore */
1805 public $resourcesToClose = array();
1807 public $call; // string; name that identifies the function called
1810 * Close all open file handles
1814 public function closeResources() {
1815 array_map( 'fclose', $this->resourcesToClose
);
1820 * FileBackendStore helper function to handle listings that span container shards.
1821 * Do not use this class from places outside of FileBackendStore.
1823 * @ingroup FileBackend
1825 abstract class FileBackendStoreShardListIterator
extends FilterIterator
{
1826 /** @var FileBackendStore */
1831 protected $container; // string; full container name
1832 protected $directory; // string; resolved relative path
1835 protected $multiShardPaths = array(); // (rel path => 1)
1838 * @param $backend FileBackendStore
1839 * @param string $container Full storage container name
1840 * @param string $dir Storage directory relative to container
1841 * @param array $suffixes List of container shard suffixes
1842 * @param array $params
1844 public function __construct(
1845 FileBackendStore
$backend, $container, $dir, array $suffixes, array $params
1847 $this->backend
= $backend;
1848 $this->container
= $container;
1849 $this->directory
= $dir;
1850 $this->params
= $params;
1852 $iter = new AppendIterator();
1853 foreach ( $suffixes as $suffix ) {
1854 $iter->append( $this->listFromShard( $this->container
. $suffix ) );
1857 parent
::__construct( $iter );
1860 public function accept() {
1861 $rel = $this->getInnerIterator()->current(); // path relative to given directory
1862 $path = $this->params
['dir'] . "/{$rel}"; // full storage path
1863 if ( $this->backend
->isSingleShardPathInternal( $path ) ) {
1864 return true; // path is only on one shard; no issue with duplicates
1865 } elseif ( isset( $this->multiShardPaths
[$rel] ) ) {
1866 // Don't keep listing paths that are on multiple shards
1869 $this->multiShardPaths
[$rel] = 1;
1874 public function rewind() {
1876 $this->multiShardPaths
= array();
1880 * Get the list for a given container shard
1882 * @param string $container Resolved container name
1885 abstract protected function listFromShard( $container );
1889 * Iterator for listing directories
1891 class FileBackendStoreShardDirIterator
extends FileBackendStoreShardListIterator
{
1892 protected function listFromShard( $container ) {
1893 $list = $this->backend
->getDirectoryListInternal(
1894 $container, $this->directory
, $this->params
);
1895 if ( $list === null ) {
1896 return new ArrayIterator( array() );
1898 return is_array( $list ) ?
new ArrayIterator( $list ) : $list;
1904 * Iterator for listing regular files
1906 class FileBackendStoreShardFileIterator
extends FileBackendStoreShardListIterator
{
1907 protected function listFromShard( $container ) {
1908 $list = $this->backend
->getFileListInternal(
1909 $container, $this->directory
, $this->params
);
1910 if ( $list === null ) {
1911 return new ArrayIterator( array() );
1913 return is_array( $list ) ?
new ArrayIterator( $list ) : $list;