3 * Base class for all backends using particular storage medium.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup FileBackend
22 * @author Aaron Schulz
26 * @brief Base class for all backends using particular storage medium.
28 * This class defines the methods as abstract that subclasses must implement.
29 * Outside callers should *not* use functions with "Internal" in the name.
31 * The FileBackend operations are implemented using basic functions
32 * such as storeInternal(), copyInternal(), deleteInternal() and the like.
33 * This class is also responsible for path resolution and sanitization.
35 * @ingroup FileBackend
38 abstract class FileBackendStore
extends FileBackend
{
41 /** @var ProcessCacheLRU */
42 protected $cheapCache; // Map of paths to small (RAM/disk) cache items
43 /** @var ProcessCacheLRU */
44 protected $expensiveCache; // Map of paths to large (RAM/disk) cache items
46 /** @var Array Map of container names to sharding settings */
47 protected $shardViaHashLevels = array(); // (container name => config array)
49 protected $maxFileSize = 4294967296; // integer bytes (4GiB)
51 const CACHE_TTL
= 10; // integer; TTL in seconds for process cache entries
54 * @see FileBackend::__construct()
56 * @param $config Array
58 public function __construct( array $config ) {
59 parent
::__construct( $config );
60 $this->memCache
= new EmptyBagOStuff(); // disabled by default
61 $this->cheapCache
= new ProcessCacheLRU( 300 );
62 $this->expensiveCache
= new ProcessCacheLRU( 5 );
66 * Get the maximum allowable file size given backend
67 * medium restrictions and basic performance constraints.
68 * Do not call this function from places outside FileBackend and FileOp.
70 * @return integer Bytes
72 final public function maxFileSizeInternal() {
73 return $this->maxFileSize
;
77 * Check if a file can be created or changed at a given storage path.
78 * FS backends should check if the parent directory exists, files can be
79 * written under it, and that any file already there is writable.
80 * Backends using key/value stores should check if the container exists.
82 * @param $storagePath string
85 abstract public function isPathUsableInternal( $storagePath );
88 * Create a file in the backend with the given contents.
89 * This will overwrite any file that exists at the destination.
90 * Do not call this function from places outside FileBackend and FileOp.
93 * - content : the raw file contents
94 * - dst : destination storage path
95 * - disposition : Content-Disposition header value for the destination
96 * - headers : HTTP header name/value map
97 * - async : Status will be returned immediately if supported.
98 * If the status is OK, then its value field will be
99 * set to a FileBackendStoreOpHandle object.
101 * @param $params Array
104 final public function createInternal( array $params ) {
105 wfProfileIn( __METHOD__
);
106 wfProfileIn( __METHOD__
. '-' . $this->name
);
107 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
108 $status = Status
::newFatal( 'backend-fail-maxsize',
109 $params['dst'], $this->maxFileSizeInternal() );
111 $status = $this->doCreateInternal( $params );
112 $this->clearCache( array( $params['dst'] ) );
113 $this->deleteFileCache( $params['dst'] ); // persistent cache
115 wfProfileOut( __METHOD__
. '-' . $this->name
);
116 wfProfileOut( __METHOD__
);
121 * @see FileBackendStore::createInternal()
124 abstract protected function doCreateInternal( array $params );
127 * Store a file into the backend from a file on disk.
128 * This will overwrite any file that exists at the destination.
129 * Do not call this function from places outside FileBackend and FileOp.
132 * - src : source path on disk
133 * - dst : destination storage path
134 * - disposition : Content-Disposition header value for the destination
135 * - headers : HTTP header name/value map
136 * - async : Status will be returned immediately if supported.
137 * If the status is OK, then its value field will be
138 * set to a FileBackendStoreOpHandle object.
140 * @param $params Array
143 final public function storeInternal( array $params ) {
144 wfProfileIn( __METHOD__
);
145 wfProfileIn( __METHOD__
. '-' . $this->name
);
146 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
147 $status = Status
::newFatal( 'backend-fail-maxsize',
148 $params['dst'], $this->maxFileSizeInternal() );
150 $status = $this->doStoreInternal( $params );
151 $this->clearCache( array( $params['dst'] ) );
152 $this->deleteFileCache( $params['dst'] ); // persistent cache
154 wfProfileOut( __METHOD__
. '-' . $this->name
);
155 wfProfileOut( __METHOD__
);
160 * @see FileBackendStore::storeInternal()
163 abstract protected function doStoreInternal( array $params );
166 * Copy a file from one storage path to another in the backend.
167 * This will overwrite any file that exists at the destination.
168 * Do not call this function from places outside FileBackend and FileOp.
171 * - src : source storage path
172 * - dst : destination storage path
173 * - ignoreMissingSource : do nothing if the source file does not exist
174 * - disposition : Content-Disposition header value for the destination
175 * - async : Status will be returned immediately if supported.
176 * If the status is OK, then its value field will be
177 * set to a FileBackendStoreOpHandle object.
179 * @param $params Array
182 final public function copyInternal( array $params ) {
183 wfProfileIn( __METHOD__
);
184 wfProfileIn( __METHOD__
. '-' . $this->name
);
185 $status = $this->doCopyInternal( $params );
186 $this->clearCache( array( $params['dst'] ) );
187 $this->deleteFileCache( $params['dst'] ); // persistent cache
188 wfProfileOut( __METHOD__
. '-' . $this->name
);
189 wfProfileOut( __METHOD__
);
194 * @see FileBackendStore::copyInternal()
197 abstract protected function doCopyInternal( array $params );
200 * Delete a file at the storage path.
201 * Do not call this function from places outside FileBackend and FileOp.
204 * - src : source storage path
205 * - ignoreMissingSource : do nothing if the source file does not exist
206 * - async : Status will be returned immediately if supported.
207 * If the status is OK, then its value field will be
208 * set to a FileBackendStoreOpHandle object.
210 * @param $params Array
213 final public function deleteInternal( array $params ) {
214 wfProfileIn( __METHOD__
);
215 wfProfileIn( __METHOD__
. '-' . $this->name
);
216 $status = $this->doDeleteInternal( $params );
217 $this->clearCache( array( $params['src'] ) );
218 $this->deleteFileCache( $params['src'] ); // persistent cache
219 wfProfileOut( __METHOD__
. '-' . $this->name
);
220 wfProfileOut( __METHOD__
);
225 * @see FileBackendStore::deleteInternal()
228 abstract protected function doDeleteInternal( array $params );
231 * Move a file from one storage path to another in the backend.
232 * This will overwrite any file that exists at the destination.
233 * Do not call this function from places outside FileBackend and FileOp.
236 * - src : source storage path
237 * - dst : destination storage path
238 * - ignoreMissingSource : do nothing if the source file does not exist
239 * - disposition : Content-Disposition header value for the destination
240 * - async : Status will be returned immediately if supported.
241 * If the status is OK, then its value field will be
242 * set to a FileBackendStoreOpHandle object.
244 * @param $params Array
247 final public function moveInternal( array $params ) {
248 wfProfileIn( __METHOD__
);
249 wfProfileIn( __METHOD__
. '-' . $this->name
);
250 $status = $this->doMoveInternal( $params );
251 $this->clearCache( array( $params['src'], $params['dst'] ) );
252 $this->deleteFileCache( $params['src'] ); // persistent cache
253 $this->deleteFileCache( $params['dst'] ); // persistent cache
254 wfProfileOut( __METHOD__
. '-' . $this->name
);
255 wfProfileOut( __METHOD__
);
260 * @see FileBackendStore::moveInternal()
263 protected function doMoveInternal( array $params ) {
264 unset( $params['async'] ); // two steps, won't work here :)
265 // Copy source to dest
266 $status = $this->copyInternal( $params );
267 if ( $status->isOK() ) {
268 // Delete source (only fails due to races or medium going down)
269 $status->merge( $this->deleteInternal( array( 'src' => $params['src'] ) ) );
270 $status->setResult( true, $status->value
); // ignore delete() errors
276 * Alter metadata for a file at the storage path.
277 * Do not call this function from places outside FileBackend and FileOp.
280 * - src : source storage path
281 * - disposition : Content-Disposition header value for the destination
282 * - headers : HTTP header name/value map
283 * - async : Status will be returned immediately if supported.
284 * If the status is OK, then its value field will be
285 * set to a FileBackendStoreOpHandle object.
287 * @param $params Array
290 final public function describeInternal( array $params ) {
291 wfProfileIn( __METHOD__
);
292 wfProfileIn( __METHOD__
. '-' . $this->name
);
293 $status = $this->doDescribeInternal( $params );
294 $this->clearCache( array( $params['src'] ) );
295 $this->deleteFileCache( $params['src'] ); // persistent cache
296 wfProfileOut( __METHOD__
. '-' . $this->name
);
297 wfProfileOut( __METHOD__
);
302 * @see FileBackendStore::describeInternal()
305 protected function doDescribeInternal( array $params ) {
306 return Status
::newGood();
310 * No-op file operation that does nothing.
311 * Do not call this function from places outside FileBackend and FileOp.
313 * @param $params Array
316 final public function nullInternal( array $params ) {
317 return Status
::newGood();
321 * @see FileBackend::concatenate()
324 final public function concatenate( array $params ) {
325 wfProfileIn( __METHOD__
);
326 wfProfileIn( __METHOD__
. '-' . $this->name
);
327 $status = Status
::newGood();
329 // Try to lock the source files for the scope of this function
330 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager
::LOCK_UW
, $status );
331 if ( $status->isOK() ) {
332 // Actually do the file concatenation...
333 $start_time = microtime( true );
334 $status->merge( $this->doConcatenate( $params ) );
335 $sec = microtime( true ) - $start_time;
336 if ( !$status->isOK() ) {
337 wfDebugLog( 'FileOperation', get_class( $this ) . " failed to concatenate " .
338 count( $params['srcs'] ) . " file(s) [$sec sec]" );
342 wfProfileOut( __METHOD__
. '-' . $this->name
);
343 wfProfileOut( __METHOD__
);
348 * @see FileBackendStore::concatenate()
351 protected function doConcatenate( array $params ) {
352 $status = Status
::newGood();
353 $tmpPath = $params['dst']; // convenience
354 unset( $params['latest'] ); // sanity
356 // Check that the specified temp file is valid...
357 wfSuppressWarnings();
358 $ok = ( is_file( $tmpPath ) && filesize( $tmpPath ) == 0 );
360 if ( !$ok ) { // not present or not empty
361 $status->fatal( 'backend-fail-opentemp', $tmpPath );
365 // Get local FS versions of the chunks needed for the concatenation...
366 $fsFiles = $this->getLocalReferenceMulti( $params );
367 foreach ( $fsFiles as $path => &$fsFile ) {
368 if ( !$fsFile ) { // chunk failed to download?
369 $fsFile = $this->getLocalReference( array( 'src' => $path ) );
370 if ( !$fsFile ) { // retry failed?
371 $status->fatal( 'backend-fail-read', $path );
376 unset( $fsFile ); // unset reference so we can reuse $fsFile
378 // Get a handle for the destination temp file
379 $tmpHandle = fopen( $tmpPath, 'ab' );
380 if ( $tmpHandle === false ) {
381 $status->fatal( 'backend-fail-opentemp', $tmpPath );
385 // Build up the temp file using the source chunks (in order)...
386 foreach ( $fsFiles as $virtualSource => $fsFile ) {
387 // Get a handle to the local FS version
388 $sourceHandle = fopen( $fsFile->getPath(), 'rb' );
389 if ( $sourceHandle === false ) {
390 fclose( $tmpHandle );
391 $status->fatal( 'backend-fail-read', $virtualSource );
394 // Append chunk to file (pass chunk size to avoid magic quotes)
395 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
396 fclose( $sourceHandle );
397 fclose( $tmpHandle );
398 $status->fatal( 'backend-fail-writetemp', $tmpPath );
401 fclose( $sourceHandle );
403 if ( !fclose( $tmpHandle ) ) {
404 $status->fatal( 'backend-fail-closetemp', $tmpPath );
408 clearstatcache(); // temp file changed
414 * @see FileBackend::doPrepare()
417 final protected function doPrepare( array $params ) {
418 wfProfileIn( __METHOD__
);
419 wfProfileIn( __METHOD__
. '-' . $this->name
);
421 $status = Status
::newGood();
422 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
423 if ( $dir === null ) {
424 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
425 wfProfileOut( __METHOD__
. '-' . $this->name
);
426 wfProfileOut( __METHOD__
);
427 return $status; // invalid storage path
430 if ( $shard !== null ) { // confined to a single container/shard
431 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
432 } else { // directory is on several shards
433 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
434 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
435 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
436 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
440 wfProfileOut( __METHOD__
. '-' . $this->name
);
441 wfProfileOut( __METHOD__
);
446 * @see FileBackendStore::doPrepare()
449 protected function doPrepareInternal( $container, $dir, array $params ) {
450 return Status
::newGood();
454 * @see FileBackend::doSecure()
457 final protected function doSecure( array $params ) {
458 wfProfileIn( __METHOD__
);
459 wfProfileIn( __METHOD__
. '-' . $this->name
);
460 $status = Status
::newGood();
462 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
463 if ( $dir === null ) {
464 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
465 wfProfileOut( __METHOD__
. '-' . $this->name
);
466 wfProfileOut( __METHOD__
);
467 return $status; // invalid storage path
470 if ( $shard !== null ) { // confined to a single container/shard
471 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
472 } else { // directory is on several shards
473 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
474 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
475 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
476 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
480 wfProfileOut( __METHOD__
. '-' . $this->name
);
481 wfProfileOut( __METHOD__
);
486 * @see FileBackendStore::doSecure()
489 protected function doSecureInternal( $container, $dir, array $params ) {
490 return Status
::newGood();
494 * @see FileBackend::doPublish()
497 final protected function doPublish( array $params ) {
498 wfProfileIn( __METHOD__
);
499 wfProfileIn( __METHOD__
. '-' . $this->name
);
500 $status = Status
::newGood();
502 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
503 if ( $dir === null ) {
504 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
505 wfProfileOut( __METHOD__
. '-' . $this->name
);
506 wfProfileOut( __METHOD__
);
507 return $status; // invalid storage path
510 if ( $shard !== null ) { // confined to a single container/shard
511 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
512 } else { // directory is on several shards
513 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
514 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
515 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
516 $status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
520 wfProfileOut( __METHOD__
. '-' . $this->name
);
521 wfProfileOut( __METHOD__
);
526 * @see FileBackendStore::doPublish()
529 protected function doPublishInternal( $container, $dir, array $params ) {
530 return Status
::newGood();
534 * @see FileBackend::doClean()
537 final protected function doClean( array $params ) {
538 wfProfileIn( __METHOD__
);
539 wfProfileIn( __METHOD__
. '-' . $this->name
);
540 $status = Status
::newGood();
542 // Recursive: first delete all empty subdirs recursively
543 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
544 $subDirsRel = $this->getTopDirectoryList( array( 'dir' => $params['dir'] ) );
545 if ( $subDirsRel !== null ) { // no errors
546 foreach ( $subDirsRel as $subDirRel ) {
547 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
548 $status->merge( $this->doClean( array( 'dir' => $subDir ) +
$params ) );
550 unset( $subDirsRel ); // free directory for rmdir() on Windows (for FS backends)
554 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
555 if ( $dir === null ) {
556 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
557 wfProfileOut( __METHOD__
. '-' . $this->name
);
558 wfProfileOut( __METHOD__
);
559 return $status; // invalid storage path
562 // Attempt to lock this directory...
563 $filesLockEx = array( $params['dir'] );
564 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
565 if ( !$status->isOK() ) {
566 wfProfileOut( __METHOD__
. '-' . $this->name
);
567 wfProfileOut( __METHOD__
);
568 return $status; // abort
571 if ( $shard !== null ) { // confined to a single container/shard
572 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
573 $this->deleteContainerCache( $fullCont ); // purge cache
574 } else { // directory is on several shards
575 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
576 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
577 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
578 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
579 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
583 wfProfileOut( __METHOD__
. '-' . $this->name
);
584 wfProfileOut( __METHOD__
);
589 * @see FileBackendStore::doClean()
592 protected function doCleanInternal( $container, $dir, array $params ) {
593 return Status
::newGood();
597 * @see FileBackend::fileExists()
600 final public function fileExists( array $params ) {
601 wfProfileIn( __METHOD__
);
602 wfProfileIn( __METHOD__
. '-' . $this->name
);
603 $stat = $this->getFileStat( $params );
604 wfProfileOut( __METHOD__
. '-' . $this->name
);
605 wfProfileOut( __METHOD__
);
606 return ( $stat === null ) ?
null : (bool)$stat; // null => failure
610 * @see FileBackend::getFileTimestamp()
613 final public function getFileTimestamp( array $params ) {
614 wfProfileIn( __METHOD__
);
615 wfProfileIn( __METHOD__
. '-' . $this->name
);
616 $stat = $this->getFileStat( $params );
617 wfProfileOut( __METHOD__
. '-' . $this->name
);
618 wfProfileOut( __METHOD__
);
619 return $stat ?
$stat['mtime'] : false;
623 * @see FileBackend::getFileSize()
626 final public function getFileSize( array $params ) {
627 wfProfileIn( __METHOD__
);
628 wfProfileIn( __METHOD__
. '-' . $this->name
);
629 $stat = $this->getFileStat( $params );
630 wfProfileOut( __METHOD__
. '-' . $this->name
);
631 wfProfileOut( __METHOD__
);
632 return $stat ?
$stat['size'] : false;
636 * @see FileBackend::getFileStat()
639 final public function getFileStat( array $params ) {
640 $path = self
::normalizeStoragePath( $params['src'] );
641 if ( $path === null ) {
642 return false; // invalid storage path
644 wfProfileIn( __METHOD__
);
645 wfProfileIn( __METHOD__
. '-' . $this->name
);
646 $latest = !empty( $params['latest'] ); // use latest data?
647 if ( !$this->cheapCache
->has( $path, 'stat', self
::CACHE_TTL
) ) {
648 $this->primeFileCache( array( $path ) ); // check persistent cache
650 if ( $this->cheapCache
->has( $path, 'stat', self
::CACHE_TTL
) ) {
651 $stat = $this->cheapCache
->get( $path, 'stat' );
652 // If we want the latest data, check that this cached
653 // value was in fact fetched with the latest available data
654 // (the process cache is ignored if it contains a negative).
655 if ( !$latest ||
( is_array( $stat ) && $stat['latest'] ) ) {
656 wfProfileOut( __METHOD__
. '-' . $this->name
);
657 wfProfileOut( __METHOD__
);
661 wfProfileIn( __METHOD__
. '-miss' );
662 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
663 $stat = $this->doGetFileStat( $params );
664 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
665 wfProfileOut( __METHOD__
. '-miss' );
666 if ( is_array( $stat ) ) { // file exists
667 $stat['latest'] = $latest;
668 $this->cheapCache
->set( $path, 'stat', $stat );
669 $this->setFileCache( $path, $stat ); // update persistent cache
670 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
671 $this->cheapCache
->set( $path, 'sha1',
672 array( 'hash' => $stat['sha1'], 'latest' => $latest ) );
674 } elseif ( $stat === false ) { // file does not exist
675 $this->cheapCache
->set( $path, 'stat', false );
676 wfDebug( __METHOD__
. ": File $path does not exist.\n" );
677 } else { // an error occurred
678 wfDebug( __METHOD__
. ": Could not stat file $path.\n" );
680 wfProfileOut( __METHOD__
. '-' . $this->name
);
681 wfProfileOut( __METHOD__
);
686 * @see FileBackendStore::getFileStat()
688 abstract protected function doGetFileStat( array $params );
691 * @see FileBackend::getFileContentsMulti()
694 public function getFileContentsMulti( array $params ) {
695 wfProfileIn( __METHOD__
);
696 wfProfileIn( __METHOD__
. '-' . $this->name
);
698 $params = $this->setConcurrencyFlags( $params );
699 $contents = $this->doGetFileContentsMulti( $params );
701 wfProfileOut( __METHOD__
. '-' . $this->name
);
702 wfProfileOut( __METHOD__
);
707 * @see FileBackendStore::getFileContentsMulti()
710 protected function doGetFileContentsMulti( array $params ) {
712 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
713 wfSuppressWarnings();
714 $contents[$path] = $fsFile ?
file_get_contents( $fsFile->getPath() ) : false;
721 * @see FileBackend::getFileSha1Base36()
722 * @return bool|string
724 final public function getFileSha1Base36( array $params ) {
725 $path = self
::normalizeStoragePath( $params['src'] );
726 if ( $path === null ) {
727 return false; // invalid storage path
729 wfProfileIn( __METHOD__
);
730 wfProfileIn( __METHOD__
. '-' . $this->name
);
731 $latest = !empty( $params['latest'] ); // use latest data?
732 if ( $this->cheapCache
->has( $path, 'sha1', self
::CACHE_TTL
) ) {
733 $stat = $this->cheapCache
->get( $path, 'sha1' );
734 // If we want the latest data, check that this cached
735 // value was in fact fetched with the latest available data.
736 if ( !$latest ||
$stat['latest'] ) {
737 wfProfileOut( __METHOD__
. '-' . $this->name
);
738 wfProfileOut( __METHOD__
);
739 return $stat['hash'];
742 wfProfileIn( __METHOD__
. '-miss' );
743 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
744 $hash = $this->doGetFileSha1Base36( $params );
745 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
746 wfProfileOut( __METHOD__
. '-miss' );
747 if ( $hash ) { // don't cache negatives
748 $this->cheapCache
->set( $path, 'sha1',
749 array( 'hash' => $hash, 'latest' => $latest ) );
751 wfProfileOut( __METHOD__
. '-' . $this->name
);
752 wfProfileOut( __METHOD__
);
757 * @see FileBackendStore::getFileSha1Base36()
758 * @return bool|string
760 protected function doGetFileSha1Base36( array $params ) {
761 $fsFile = $this->getLocalReference( $params );
765 return $fsFile->getSha1Base36();
770 * @see FileBackend::getFileProps()
773 final public function getFileProps( array $params ) {
774 wfProfileIn( __METHOD__
);
775 wfProfileIn( __METHOD__
. '-' . $this->name
);
776 $fsFile = $this->getLocalReference( $params );
777 $props = $fsFile ?
$fsFile->getProps() : FSFile
::placeholderProps();
778 wfProfileOut( __METHOD__
. '-' . $this->name
);
779 wfProfileOut( __METHOD__
);
784 * @see FileBackend::getLocalReferenceMulti()
787 final public function getLocalReferenceMulti( array $params ) {
788 wfProfileIn( __METHOD__
);
789 wfProfileIn( __METHOD__
. '-' . $this->name
);
791 $params = $this->setConcurrencyFlags( $params );
793 $fsFiles = array(); // (path => FSFile)
794 $latest = !empty( $params['latest'] ); // use latest data?
795 // Reuse any files already in process cache...
796 foreach ( $params['srcs'] as $src ) {
797 $path = self
::normalizeStoragePath( $src );
798 if ( $path === null ) {
799 $fsFiles[$src] = null; // invalid storage path
800 } elseif ( $this->expensiveCache
->has( $path, 'localRef' ) ) {
801 $val = $this->expensiveCache
->get( $path, 'localRef' );
802 // If we want the latest data, check that this cached
803 // value was in fact fetched with the latest available data.
804 if ( !$latest ||
$val['latest'] ) {
805 $fsFiles[$src] = $val['object'];
809 // Fetch local references of any remaning files...
810 $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
811 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
812 $fsFiles[$path] = $fsFile;
813 if ( $fsFile ) { // update the process cache...
814 $this->expensiveCache
->set( $path, 'localRef',
815 array( 'object' => $fsFile, 'latest' => $latest ) );
819 wfProfileOut( __METHOD__
. '-' . $this->name
);
820 wfProfileOut( __METHOD__
);
825 * @see FileBackendStore::getLocalReferenceMulti()
828 protected function doGetLocalReferenceMulti( array $params ) {
829 return $this->doGetLocalCopyMulti( $params );
833 * @see FileBackend::getLocalCopyMulti()
836 final public function getLocalCopyMulti( array $params ) {
837 wfProfileIn( __METHOD__
);
838 wfProfileIn( __METHOD__
. '-' . $this->name
);
840 $params = $this->setConcurrencyFlags( $params );
841 $tmpFiles = $this->doGetLocalCopyMulti( $params );
843 wfProfileOut( __METHOD__
. '-' . $this->name
);
844 wfProfileOut( __METHOD__
);
849 * @see FileBackendStore::getLocalCopyMulti()
852 abstract protected function doGetLocalCopyMulti( array $params );
855 * @see FileBackend::getFileHttpUrl()
856 * @return string|null
858 public function getFileHttpUrl( array $params ) {
859 return null; // not supported
863 * @see FileBackend::streamFile()
866 final public function streamFile( array $params ) {
867 wfProfileIn( __METHOD__
);
868 wfProfileIn( __METHOD__
. '-' . $this->name
);
869 $status = Status
::newGood();
871 $info = $this->getFileStat( $params );
872 if ( !$info ) { // let StreamFile handle the 404
873 $status->fatal( 'backend-fail-notexists', $params['src'] );
876 // Set output buffer and HTTP headers for stream
877 $extraHeaders = isset( $params['headers'] ) ?
$params['headers'] : array();
878 $res = StreamFile
::prepareForStream( $params['src'], $info, $extraHeaders );
879 if ( $res == StreamFile
::NOT_MODIFIED
) {
880 // do nothing; client cache is up to date
881 } elseif ( $res == StreamFile
::READY_STREAM
) {
882 wfProfileIn( __METHOD__
. '-send' );
883 wfProfileIn( __METHOD__
. '-send-' . $this->name
);
884 $status = $this->doStreamFile( $params );
885 wfProfileOut( __METHOD__
. '-send-' . $this->name
);
886 wfProfileOut( __METHOD__
. '-send' );
887 if ( !$status->isOK() ) {
888 // Per bug 41113, nasty things can happen if bad cache entries get
889 // stuck in cache. It's also possible that this error can come up
890 // with simple race conditions. Clear out the stat cache to be safe.
891 $this->clearCache( array( $params['src'] ) );
892 $this->deleteFileCache( $params['src'] );
893 trigger_error( "Bad stat cache or race condition for file {$params['src']}." );
896 $status->fatal( 'backend-fail-stream', $params['src'] );
899 wfProfileOut( __METHOD__
. '-' . $this->name
);
900 wfProfileOut( __METHOD__
);
905 * @see FileBackendStore::streamFile()
908 protected function doStreamFile( array $params ) {
909 $status = Status
::newGood();
911 $fsFile = $this->getLocalReference( $params );
913 $status->fatal( 'backend-fail-stream', $params['src'] );
914 } elseif ( !readfile( $fsFile->getPath() ) ) {
915 $status->fatal( 'backend-fail-stream', $params['src'] );
922 * @see FileBackend::directoryExists()
925 final public function directoryExists( array $params ) {
926 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
927 if ( $dir === null ) {
928 return false; // invalid storage path
930 if ( $shard !== null ) { // confined to a single container/shard
931 return $this->doDirectoryExists( $fullCont, $dir, $params );
932 } else { // directory is on several shards
933 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
934 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
935 $res = false; // response
936 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
937 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
941 } elseif ( $exists === null ) { // error?
942 $res = null; // if we don't find anything, it is indeterminate
950 * @see FileBackendStore::directoryExists()
952 * @param $container string Resolved container name
953 * @param $dir string Resolved path relative to container
954 * @param $params Array
957 abstract protected function doDirectoryExists( $container, $dir, array $params );
960 * @see FileBackend::getDirectoryList()
961 * @return Traversable|Array|null Returns null on failure
963 final public function getDirectoryList( array $params ) {
964 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
965 if ( $dir === null ) { // invalid storage path
968 if ( $shard !== null ) {
969 // File listing is confined to a single container/shard
970 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
972 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
973 // File listing spans multiple containers/shards
974 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
975 return new FileBackendStoreShardDirIterator( $this,
976 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
981 * Do not call this function from places outside FileBackend
983 * @see FileBackendStore::getDirectoryList()
985 * @param $container string Resolved container name
986 * @param $dir string Resolved path relative to container
987 * @param $params Array
988 * @return Traversable|Array|null Returns null on failure
990 abstract public function getDirectoryListInternal( $container, $dir, array $params );
993 * @see FileBackend::getFileList()
994 * @return Traversable|Array|null Returns null on failure
996 final public function getFileList( array $params ) {
997 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
998 if ( $dir === null ) { // invalid storage path
1001 if ( $shard !== null ) {
1002 // File listing is confined to a single container/shard
1003 return $this->getFileListInternal( $fullCont, $dir, $params );
1005 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
1006 // File listing spans multiple containers/shards
1007 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
1008 return new FileBackendStoreShardFileIterator( $this,
1009 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
1014 * Do not call this function from places outside FileBackend
1016 * @see FileBackendStore::getFileList()
1018 * @param $container string Resolved container name
1019 * @param $dir string Resolved path relative to container
1020 * @param $params Array
1021 * @return Traversable|Array|null Returns null on failure
1023 abstract public function getFileListInternal( $container, $dir, array $params );
1026 * Return a list of FileOp objects from a list of operations.
1027 * Do not call this function from places outside FileBackend.
1029 * The result must have the same number of items as the input.
1030 * An exception is thrown if an unsupported operation is requested.
1032 * @param $ops Array Same format as doOperations()
1033 * @return Array List of FileOp objects
1034 * @throws MWException
1036 final public function getOperationsInternal( array $ops ) {
1037 $supportedOps = array(
1038 'store' => 'StoreFileOp',
1039 'copy' => 'CopyFileOp',
1040 'move' => 'MoveFileOp',
1041 'delete' => 'DeleteFileOp',
1042 'create' => 'CreateFileOp',
1043 'describe' => 'DescribeFileOp',
1044 'null' => 'NullFileOp'
1047 $performOps = array(); // array of FileOp objects
1048 // Build up ordered array of FileOps...
1049 foreach ( $ops as $operation ) {
1050 $opName = $operation['op'];
1051 if ( isset( $supportedOps[$opName] ) ) {
1052 $class = $supportedOps[$opName];
1053 // Get params for this operation
1054 $params = $operation;
1055 // Append the FileOp class
1056 $performOps[] = new $class( $this, $params );
1058 throw new MWException( "Operation '$opName' is not supported." );
1066 * Get a list of storage paths to lock for a list of operations
1067 * Returns an array with 'sh' (shared) and 'ex' (exclusive) keys,
1068 * each corresponding to a list of storage paths to be locked.
1069 * All returned paths are normalized.
1071 * @param $performOps Array List of FileOp objects
1072 * @return Array ('sh' => list of paths, 'ex' => list of paths)
1074 final public function getPathsToLockForOpsInternal( array $performOps ) {
1075 // Build up a list of files to lock...
1076 $paths = array( 'sh' => array(), 'ex' => array() );
1077 foreach ( $performOps as $fileOp ) {
1078 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1079 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1081 // Optimization: if doing an EX lock anyway, don't also set an SH one
1082 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1083 // Get a shared lock on the parent directory of each path changed
1084 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1090 * @see FileBackend::getScopedLocksForOps()
1093 public function getScopedLocksForOps( array $ops, Status
$status ) {
1094 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1096 $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status ),
1097 $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status )
1102 * @see FileBackend::doOperationsInternal()
1105 final protected function doOperationsInternal( array $ops, array $opts ) {
1106 wfProfileIn( __METHOD__
);
1107 wfProfileIn( __METHOD__
. '-' . $this->name
);
1108 $status = Status
::newGood();
1110 // Fix up custom header name/value pairs...
1111 $ops = array_map( array( $this, 'stripInvalidHeadersFromOp' ), $ops );
1113 // Build up a list of FileOps...
1114 $performOps = $this->getOperationsInternal( $ops );
1116 // Acquire any locks as needed...
1117 if ( empty( $opts['nonLocking'] ) ) {
1118 // Build up a list of files to lock...
1119 $paths = $this->getPathsToLockForOpsInternal( $performOps );
1120 // Try to lock those files for the scope of this function...
1121 $scopeLockS = $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status );
1122 $scopeLockE = $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status );
1123 if ( !$status->isOK() ) {
1124 wfProfileOut( __METHOD__
. '-' . $this->name
);
1125 wfProfileOut( __METHOD__
);
1126 return $status; // abort
1130 // Clear any file cache entries (after locks acquired)
1131 if ( empty( $opts['preserveCache'] ) ) {
1132 $this->clearCache();
1135 // Load from the persistent file and container caches
1136 $this->primeFileCache( $performOps );
1137 $this->primeContainerCache( $performOps );
1139 // Actually attempt the operation batch...
1140 $opts = $this->setConcurrencyFlags( $opts );
1141 $subStatus = FileOpBatch
::attempt( $performOps, $opts, $this->fileJournal
);
1143 // Merge errors into status fields
1144 $status->merge( $subStatus );
1145 $status->success
= $subStatus->success
; // not done in merge()
1147 wfProfileOut( __METHOD__
. '-' . $this->name
);
1148 wfProfileOut( __METHOD__
);
1153 * @see FileBackend::doQuickOperationsInternal()
1155 * @throws MWException
1157 final protected function doQuickOperationsInternal( array $ops ) {
1158 wfProfileIn( __METHOD__
);
1159 wfProfileIn( __METHOD__
. '-' . $this->name
);
1160 $status = Status
::newGood();
1162 // Fix up custom header name/value pairs...
1163 $ops = array_map( array( $this, 'stripInvalidHeadersFromOp' ), $ops );
1165 // Clear any file cache entries
1166 $this->clearCache();
1168 $supportedOps = array( 'create', 'store', 'copy', 'move', 'delete', 'null' );
1169 $async = ( $this->parallelize
=== 'implicit' );
1170 $maxConcurrency = $this->concurrency
; // throttle
1172 $statuses = array(); // array of (index => Status)
1173 $fileOpHandles = array(); // list of (index => handle) arrays
1174 $curFileOpHandles = array(); // current handle batch
1175 // Perform the sync-only ops and build up op handles for the async ops...
1176 foreach ( $ops as $index => $params ) {
1177 if ( !in_array( $params['op'], $supportedOps ) ) {
1178 wfProfileOut( __METHOD__
. '-' . $this->name
);
1179 wfProfileOut( __METHOD__
);
1180 throw new MWException( "Operation '{$params['op']}' is not supported." );
1182 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1183 $subStatus = $this->$method( array( 'async' => $async ) +
$params );
1184 if ( $subStatus->value
instanceof FileBackendStoreOpHandle
) { // async
1185 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1186 $fileOpHandles[] = $curFileOpHandles; // push this batch
1187 $curFileOpHandles = array();
1189 $curFileOpHandles[$index] = $subStatus->value
; // keep index
1190 } else { // error or completed
1191 $statuses[$index] = $subStatus; // keep index
1194 if ( count( $curFileOpHandles ) ) {
1195 $fileOpHandles[] = $curFileOpHandles; // last batch
1197 // Do all the async ops that can be done concurrently...
1198 foreach ( $fileOpHandles as $fileHandleBatch ) {
1199 $statuses = $statuses +
$this->executeOpHandlesInternal( $fileHandleBatch );
1201 // Marshall and merge all the responses...
1202 foreach ( $statuses as $index => $subStatus ) {
1203 $status->merge( $subStatus );
1204 if ( $subStatus->isOK() ) {
1205 $status->success
[$index] = true;
1206 ++
$status->successCount
;
1208 $status->success
[$index] = false;
1209 ++
$status->failCount
;
1213 wfProfileOut( __METHOD__
. '-' . $this->name
);
1214 wfProfileOut( __METHOD__
);
1219 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1220 * The resulting Status object fields will correspond
1221 * to the order in which the handles where given.
1223 * @param $handles Array List of FileBackendStoreOpHandle objects
1224 * @return Array Map of Status objects
1225 * @throws MWException
1227 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1228 wfProfileIn( __METHOD__
);
1229 wfProfileIn( __METHOD__
. '-' . $this->name
);
1230 foreach ( $fileOpHandles as $fileOpHandle ) {
1231 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle
) ) {
1232 throw new MWException( "Given a non-FileBackendStoreOpHandle object." );
1233 } elseif ( $fileOpHandle->backend
->getName() !== $this->getName() ) {
1234 throw new MWException( "Given a FileBackendStoreOpHandle for the wrong backend." );
1237 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1238 foreach ( $fileOpHandles as $fileOpHandle ) {
1239 $fileOpHandle->closeResources();
1241 wfProfileOut( __METHOD__
. '-' . $this->name
);
1242 wfProfileOut( __METHOD__
);
1247 * @see FileBackendStore::executeOpHandlesInternal()
1248 * @param array $fileOpHandles
1249 * @throws MWException
1250 * @return Array List of corresponding Status objects
1252 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1253 foreach ( $fileOpHandles as $fileOpHandle ) { // OK if empty
1254 throw new MWException( "This backend supports no asynchronous operations." );
1260 * Strip long HTTP headers from a file operation
1262 * @param $op array Same format as doOperation()
1265 protected function stripInvalidHeadersFromOp( array $op ) {
1266 if ( isset( $op['headers'] ) ) {
1267 foreach ( $op['headers'] as $name => $value ) {
1268 if ( strlen( $name ) > 255 ||
strlen( $value ) > 255 ) {
1269 trigger_error( "Header '$name: $value' is too long." );
1270 unset( $op['headers'][$name] );
1271 } elseif ( !strlen( $value ) ) {
1272 $op['headers'][$name] = ''; // null/false => ""
1280 * @see FileBackend::preloadCache()
1282 final public function preloadCache( array $paths ) {
1283 $fullConts = array(); // full container names
1284 foreach ( $paths as $path ) {
1285 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1286 $fullConts[] = $fullCont;
1288 // Load from the persistent file and container caches
1289 $this->primeContainerCache( $fullConts );
1290 $this->primeFileCache( $paths );
1294 * @see FileBackend::clearCache()
1296 final public function clearCache( array $paths = null ) {
1297 if ( is_array( $paths ) ) {
1298 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1299 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1301 if ( $paths === null ) {
1302 $this->cheapCache
->clear();
1303 $this->expensiveCache
->clear();
1305 foreach ( $paths as $path ) {
1306 $this->cheapCache
->clear( $path );
1307 $this->expensiveCache
->clear( $path );
1310 $this->doClearCache( $paths );
1314 * Clears any additional stat caches for storage paths
1316 * @see FileBackend::clearCache()
1318 * @param $paths Array Storage paths (optional)
1321 protected function doClearCache( array $paths = null ) {}
1324 * Is this a key/value store where directories are just virtual?
1325 * Virtual directories exists in so much as files exists that are
1326 * prefixed with the directory path followed by a forward slash.
1330 abstract protected function directoriesAreVirtual();
1333 * Check if a container name is valid.
1334 * This checks for for length and illegal characters.
1336 * @param $container string
1339 final protected static function isValidContainerName( $container ) {
1340 // This accounts for Swift and S3 restrictions while leaving room
1341 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1342 // This disallows directory separators or traversal characters.
1343 // Note that matching strings URL encode to the same string;
1344 // in Swift, the length restriction is *after* URL encoding.
1345 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1349 * Splits a storage path into an internal container name,
1350 * an internal relative file name, and a container shard suffix.
1351 * Any shard suffix is already appended to the internal container name.
1352 * This also checks that the storage path is valid and within this backend.
1354 * If the container is sharded but a suffix could not be determined,
1355 * this means that the path can only refer to a directory and can only
1356 * be scanned by looking in all the container shards.
1358 * @param $storagePath string
1359 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1361 final protected function resolveStoragePath( $storagePath ) {
1362 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1363 if ( $backend === $this->name
) { // must be for this backend
1364 $relPath = self
::normalizeContainerPath( $relPath );
1365 if ( $relPath !== null ) {
1366 // Get shard for the normalized path if this container is sharded
1367 $cShard = $this->getContainerShard( $container, $relPath );
1368 // Validate and sanitize the relative path (backend-specific)
1369 $relPath = $this->resolveContainerPath( $container, $relPath );
1370 if ( $relPath !== null ) {
1371 // Prepend any wiki ID prefix to the container name
1372 $container = $this->fullContainerName( $container );
1373 if ( self
::isValidContainerName( $container ) ) {
1374 // Validate and sanitize the container name (backend-specific)
1375 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1376 if ( $container !== null ) {
1377 return array( $container, $relPath, $cShard );
1383 return array( null, null, null );
1387 * Like resolveStoragePath() except null values are returned if
1388 * the container is sharded and the shard could not be determined.
1390 * @see FileBackendStore::resolveStoragePath()
1392 * @param $storagePath string
1393 * @return Array (container, path) or (null, null) if invalid
1395 final protected function resolveStoragePathReal( $storagePath ) {
1396 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1397 if ( $cShard !== null ) {
1398 return array( $container, $relPath );
1400 return array( null, null );
1404 * Get the container name shard suffix for a given path.
1405 * Any empty suffix means the container is not sharded.
1407 * @param $container string Container name
1408 * @param $relPath string Storage path relative to the container
1409 * @return string|null Returns null if shard could not be determined
1411 final protected function getContainerShard( $container, $relPath ) {
1412 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1413 if ( $levels == 1 ||
$levels == 2 ) {
1414 // Hash characters are either base 16 or 36
1415 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1416 // Get a regex that represents the shard portion of paths.
1417 // The concatenation of the captures gives us the shard.
1418 if ( $levels === 1 ) { // 16 or 36 shards per container
1419 $hashDirRegex = '(' . $char . ')';
1420 } else { // 256 or 1296 shards per container
1421 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1422 $hashDirRegex = $char . '/(' . $char . '{2})';
1423 } else { // short hash dir format (e.g. "a/b/c")
1424 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1427 // Allow certain directories to be above the hash dirs so as
1428 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1429 // They must be 2+ chars to avoid any hash directory ambiguity.
1431 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1432 return '.' . implode( '', array_slice( $m, 1 ) );
1434 return null; // failed to match
1436 return ''; // no sharding
1440 * Check if a storage path maps to a single shard.
1441 * Container dirs like "a", where the container shards on "x/xy",
1442 * can reside on several shards. Such paths are tricky to handle.
1444 * @param $storagePath string Storage path
1447 final public function isSingleShardPathInternal( $storagePath ) {
1448 list( $c, $r, $shard ) = $this->resolveStoragePath( $storagePath );
1449 return ( $shard !== null );
1453 * Get the sharding config for a container.
1454 * If greater than 0, then all file storage paths within
1455 * the container are required to be hashed accordingly.
1457 * @param $container string
1458 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
1460 final protected function getContainerHashLevels( $container ) {
1461 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1462 $config = $this->shardViaHashLevels
[$container];
1463 $hashLevels = (int)$config['levels'];
1464 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1465 $hashBase = (int)$config['base'];
1466 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1467 return array( $hashLevels, $hashBase, $config['repeat'] );
1471 return array( 0, 0, false ); // no sharding
1475 * Get a list of full container shard suffixes for a container
1477 * @param $container string
1480 final protected function getContainerSuffixes( $container ) {
1482 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1483 if ( $digits > 0 ) {
1484 $numShards = pow( $base, $digits );
1485 for ( $index = 0; $index < $numShards; $index++
) {
1486 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1493 * Get the full container name, including the wiki ID prefix
1495 * @param $container string
1498 final protected function fullContainerName( $container ) {
1499 if ( $this->wikiId
!= '' ) {
1500 return "{$this->wikiId}-$container";
1507 * Resolve a container name, checking if it's allowed by the backend.
1508 * This is intended for internal use, such as encoding illegal chars.
1509 * Subclasses can override this to be more restrictive.
1511 * @param $container string
1512 * @return string|null
1514 protected function resolveContainerName( $container ) {
1519 * Resolve a relative storage path, checking if it's allowed by the backend.
1520 * This is intended for internal use, such as encoding illegal chars or perhaps
1521 * getting absolute paths (e.g. FS based backends). Note that the relative path
1522 * may be the empty string (e.g. the path is simply to the container).
1524 * @param $container string Container name
1525 * @param $relStoragePath string Storage path relative to the container
1526 * @return string|null Path or null if not valid
1528 protected function resolveContainerPath( $container, $relStoragePath ) {
1529 return $relStoragePath;
1533 * Get the cache key for a container
1535 * @param $container string Resolved container name
1538 private function containerCacheKey( $container ) {
1539 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1543 * Set the cached info for a container
1545 * @param $container string Resolved container name
1546 * @param $val mixed Information to cache
1548 final protected function setContainerCache( $container, $val ) {
1549 $this->memCache
->add( $this->containerCacheKey( $container ), $val, 14*86400 );
1553 * Delete the cached info for a container.
1554 * The cache key is salted for a while to prevent race conditions.
1556 * @param $container string Resolved container name
1558 final protected function deleteContainerCache( $container ) {
1559 if ( !$this->memCache
->set( $this->containerCacheKey( $container ), 'PURGED', 300 ) ) {
1560 trigger_error( "Unable to delete stat cache for container $container." );
1565 * Do a batch lookup from cache for container stats for all containers
1566 * used in a list of container names, storage paths, or FileOp objects.
1567 * This loads the persistent cache values into the process cache.
1569 * @param $items Array
1572 final protected function primeContainerCache( array $items ) {
1573 wfProfileIn( __METHOD__
);
1574 wfProfileIn( __METHOD__
. '-' . $this->name
);
1576 $paths = array(); // list of storage paths
1577 $contNames = array(); // (cache key => resolved container name)
1578 // Get all the paths/containers from the items...
1579 foreach ( $items as $item ) {
1580 if ( $item instanceof FileOp
) {
1581 $paths = array_merge( $paths, $item->storagePathsRead() );
1582 $paths = array_merge( $paths, $item->storagePathsChanged() );
1583 } elseif ( self
::isStoragePath( $item ) ) {
1585 } elseif ( is_string( $item ) ) { // full container name
1586 $contNames[$this->containerCacheKey( $item )] = $item;
1589 // Get all the corresponding cache keys for paths...
1590 foreach ( $paths as $path ) {
1591 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1592 if ( $fullCont !== null ) { // valid path for this backend
1593 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1597 $contInfo = array(); // (resolved container name => cache value)
1598 // Get all cache entries for these container cache keys...
1599 $values = $this->memCache
->getMulti( array_keys( $contNames ) );
1600 foreach ( $values as $cacheKey => $val ) {
1601 $contInfo[$contNames[$cacheKey]] = $val;
1604 // Populate the container process cache for the backend...
1605 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1607 wfProfileOut( __METHOD__
. '-' . $this->name
);
1608 wfProfileOut( __METHOD__
);
1612 * Fill the backend-specific process cache given an array of
1613 * resolved container names and their corresponding cached info.
1614 * Only containers that actually exist should appear in the map.
1616 * @param $containerInfo Array Map of resolved container names to cached info
1619 protected function doPrimeContainerCache( array $containerInfo ) {}
1622 * Get the cache key for a file path
1624 * @param $path string Normalized storage path
1627 private function fileCacheKey( $path ) {
1628 return wfMemcKey( 'backend', $this->getName(), 'file', sha1( $path ) );
1632 * Set the cached stat info for a file path.
1633 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1634 * salting for the case when a file is created at a path were there was none before.
1636 * @param $path string Storage path
1637 * @param $val mixed Information to cache
1639 final protected function setFileCache( $path, $val ) {
1640 $path = FileBackend
::normalizeStoragePath( $path );
1641 if ( $path === null ) {
1642 return; // invalid storage path
1644 $this->memCache
->add( $this->fileCacheKey( $path ), $val, 7*86400 );
1648 * Delete the cached stat info for a file path.
1649 * The cache key is salted for a while to prevent race conditions.
1651 * @param $path string Storage path
1653 final protected function deleteFileCache( $path ) {
1654 $path = FileBackend
::normalizeStoragePath( $path );
1655 if ( $path === null ) {
1656 return; // invalid storage path
1658 if ( !$this->memCache
->set( $this->fileCacheKey( $path ), 'PURGED', 300 ) ) {
1659 trigger_error( "Unable to delete stat cache for file $path." );
1664 * Do a batch lookup from cache for file stats for all paths
1665 * used in a list of storage paths or FileOp objects.
1666 * This loads the persistent cache values into the process cache.
1668 * @param $items Array List of storage paths or FileOps
1671 final protected function primeFileCache( array $items ) {
1672 wfProfileIn( __METHOD__
);
1673 wfProfileIn( __METHOD__
. '-' . $this->name
);
1675 $paths = array(); // list of storage paths
1676 $pathNames = array(); // (cache key => storage path)
1677 // Get all the paths/containers from the items...
1678 foreach ( $items as $item ) {
1679 if ( $item instanceof FileOp
) {
1680 $paths = array_merge( $paths, $item->storagePathsRead() );
1681 $paths = array_merge( $paths, $item->storagePathsChanged() );
1682 } elseif ( self
::isStoragePath( $item ) ) {
1683 $paths[] = FileBackend
::normalizeStoragePath( $item );
1686 // Get rid of any paths that failed normalization...
1687 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1688 // Get all the corresponding cache keys for paths...
1689 foreach ( $paths as $path ) {
1690 list( $cont, $rel, $s ) = $this->resolveStoragePath( $path );
1691 if ( $rel !== null ) { // valid path for this backend
1692 $pathNames[$this->fileCacheKey( $path )] = $path;
1695 // Get all cache entries for these container cache keys...
1696 $values = $this->memCache
->getMulti( array_keys( $pathNames ) );
1697 foreach ( $values as $cacheKey => $val ) {
1698 if ( is_array( $val ) ) {
1699 $path = $pathNames[$cacheKey];
1700 $this->cheapCache
->set( $path, 'stat', $val );
1701 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1702 $this->cheapCache
->set( $path, 'sha1',
1703 array( 'hash' => $val['sha1'], 'latest' => $val['latest'] ) );
1708 wfProfileOut( __METHOD__
. '-' . $this->name
);
1709 wfProfileOut( __METHOD__
);
1713 * Set the 'concurrency' option from a list of operation options
1715 * @param $opts array Map of operation options
1718 final protected function setConcurrencyFlags( array $opts ) {
1719 $opts['concurrency'] = 1; // off
1720 if ( $this->parallelize
=== 'implicit' ) {
1721 if ( !isset( $opts['parallelize'] ) ||
$opts['parallelize'] ) {
1722 $opts['concurrency'] = $this->concurrency
;
1724 } elseif ( $this->parallelize
=== 'explicit' ) {
1725 if ( !empty( $opts['parallelize'] ) ) {
1726 $opts['concurrency'] = $this->concurrency
;
1734 * FileBackendStore helper class for performing asynchronous file operations.
1736 * For example, calling FileBackendStore::createInternal() with the "async"
1737 * param flag may result in a Status that contains this object as a value.
1738 * This class is largely backend-specific and is mostly just "magic" to be
1739 * passed to FileBackendStore::executeOpHandlesInternal().
1741 abstract class FileBackendStoreOpHandle
{
1743 public $params = array(); // params to caller functions
1744 /** @var FileBackendStore */
1747 public $resourcesToClose = array();
1749 public $call; // string; name that identifies the function called
1752 * Close all open file handles
1756 public function closeResources() {
1757 array_map( 'fclose', $this->resourcesToClose
);
1762 * FileBackendStore helper function to handle listings that span container shards.
1763 * Do not use this class from places outside of FileBackendStore.
1765 * @ingroup FileBackend
1767 abstract class FileBackendStoreShardListIterator
implements Iterator
{
1768 /** @var FileBackendStore */
1773 protected $shardSuffixes;
1774 protected $container; // string; full container name
1775 protected $directory; // string; resolved relative path
1777 /** @var Traversable */
1779 protected $curShard = 0; // integer
1780 protected $pos = 0; // integer
1783 protected $multiShardPaths = array(); // (rel path => 1)
1786 * @param $backend FileBackendStore
1787 * @param $container string Full storage container name
1788 * @param $dir string Storage directory relative to container
1789 * @param $suffixes Array List of container shard suffixes
1790 * @param $params Array
1792 public function __construct(
1793 FileBackendStore
$backend, $container, $dir, array $suffixes, array $params
1795 $this->backend
= $backend;
1796 $this->container
= $container;
1797 $this->directory
= $dir;
1798 $this->shardSuffixes
= $suffixes;
1799 $this->params
= $params;
1803 * @see Iterator::key()
1806 public function key() {
1811 * @see Iterator::valid()
1814 public function valid() {
1815 if ( $this->iter
instanceof Iterator
) {
1816 return $this->iter
->valid();
1817 } elseif ( is_array( $this->iter
) ) {
1818 return ( current( $this->iter
) !== false ); // no paths can have this value
1820 return false; // some failure?
1824 * @see Iterator::current()
1825 * @return string|bool String or false
1827 public function current() {
1828 return ( $this->iter
instanceof Iterator
)
1829 ?
$this->iter
->current()
1830 : current( $this->iter
);
1834 * @see Iterator::next()
1837 public function next() {
1839 ( $this->iter
instanceof Iterator
) ?
$this->iter
->next() : next( $this->iter
);
1841 $continue = false; // keep scanning shards?
1842 $this->filterViaNext(); // filter out duplicates
1843 // Find the next non-empty shard if no elements are left
1844 if ( !$this->valid() ) {
1845 $this->nextShardIteratorIfNotValid();
1846 $continue = $this->valid(); // re-filter unless we ran out of shards
1848 } while ( $continue );
1852 * @see Iterator::rewind()
1855 public function rewind() {
1857 $this->curShard
= 0;
1858 $this->setIteratorFromCurrentShard();
1860 $continue = false; // keep scanning shards?
1861 $this->filterViaNext(); // filter out duplicates
1862 // Find the next non-empty shard if no elements are left
1863 if ( !$this->valid() ) {
1864 $this->nextShardIteratorIfNotValid();
1865 $continue = $this->valid(); // re-filter unless we ran out of shards
1867 } while ( $continue );
1871 * Filter out duplicate items by advancing to the next ones
1873 protected function filterViaNext() {
1874 while ( $this->valid() ) {
1875 $rel = $this->iter
->current(); // path relative to given directory
1876 $path = $this->params
['dir'] . "/{$rel}"; // full storage path
1877 if ( $this->backend
->isSingleShardPathInternal( $path ) ) {
1878 break; // path is only on one shard; no issue with duplicates
1879 } elseif ( isset( $this->multiShardPaths
[$rel] ) ) {
1880 // Don't keep listing paths that are on multiple shards
1881 ( $this->iter
instanceof Iterator
) ?
$this->iter
->next() : next( $this->iter
);
1883 $this->multiShardPaths
[$rel] = 1;
1890 * If the list iterator for this container shard is out of items,
1891 * then move on to the next container that has items.
1892 * If there are none, then it advances to the last container.
1894 protected function nextShardIteratorIfNotValid() {
1895 while ( !$this->valid() && ++
$this->curShard
< count( $this->shardSuffixes
) ) {
1896 $this->setIteratorFromCurrentShard();
1901 * Set the list iterator to that of the current container shard
1903 protected function setIteratorFromCurrentShard() {
1904 $this->iter
= $this->listFromShard(
1905 $this->container
. $this->shardSuffixes
[$this->curShard
],
1906 $this->directory
, $this->params
);
1907 // Start loading results so that current() works
1908 if ( $this->iter
) {
1909 ( $this->iter
instanceof Iterator
) ?
$this->iter
->rewind() : reset( $this->iter
);
1914 * Get the list for a given container shard
1916 * @param $container string Resolved container name
1917 * @param $dir string Resolved path relative to container
1918 * @param $params Array
1919 * @return Traversable|Array|null
1921 abstract protected function listFromShard( $container, $dir, array $params );
1925 * Iterator for listing directories
1927 class FileBackendStoreShardDirIterator
extends FileBackendStoreShardListIterator
{
1929 * @see FileBackendStoreShardListIterator::listFromShard()
1930 * @return Array|null|Traversable
1932 protected function listFromShard( $container, $dir, array $params ) {
1933 return $this->backend
->getDirectoryListInternal( $container, $dir, $params );
1938 * Iterator for listing regular files
1940 class FileBackendStoreShardFileIterator
extends FileBackendStoreShardListIterator
{
1942 * @see FileBackendStoreShardListIterator::listFromShard()
1943 * @return Array|null|Traversable
1945 protected function listFromShard( $container, $dir, array $params ) {
1946 return $this->backend
->getFileListInternal( $container, $dir, $params );