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 trigger_error( "Header value for '$name' is empty." );
1273 unset( $op['headers'][$name] ); // ignore
1281 * @see FileBackend::preloadCache()
1283 final public function preloadCache( array $paths ) {
1284 $fullConts = array(); // full container names
1285 foreach ( $paths as $path ) {
1286 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1287 $fullConts[] = $fullCont;
1289 // Load from the persistent file and container caches
1290 $this->primeContainerCache( $fullConts );
1291 $this->primeFileCache( $paths );
1295 * @see FileBackend::clearCache()
1297 final public function clearCache( array $paths = null ) {
1298 if ( is_array( $paths ) ) {
1299 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1300 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1302 if ( $paths === null ) {
1303 $this->cheapCache
->clear();
1304 $this->expensiveCache
->clear();
1306 foreach ( $paths as $path ) {
1307 $this->cheapCache
->clear( $path );
1308 $this->expensiveCache
->clear( $path );
1311 $this->doClearCache( $paths );
1315 * Clears any additional stat caches for storage paths
1317 * @see FileBackend::clearCache()
1319 * @param $paths Array Storage paths (optional)
1322 protected function doClearCache( array $paths = null ) {}
1325 * Is this a key/value store where directories are just virtual?
1326 * Virtual directories exists in so much as files exists that are
1327 * prefixed with the directory path followed by a forward slash.
1331 abstract protected function directoriesAreVirtual();
1334 * Check if a container name is valid.
1335 * This checks for for length and illegal characters.
1337 * @param $container string
1340 final protected static function isValidContainerName( $container ) {
1341 // This accounts for Swift and S3 restrictions while leaving room
1342 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1343 // This disallows directory separators or traversal characters.
1344 // Note that matching strings URL encode to the same string;
1345 // in Swift, the length restriction is *after* URL encoding.
1346 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1350 * Splits a storage path into an internal container name,
1351 * an internal relative file name, and a container shard suffix.
1352 * Any shard suffix is already appended to the internal container name.
1353 * This also checks that the storage path is valid and within this backend.
1355 * If the container is sharded but a suffix could not be determined,
1356 * this means that the path can only refer to a directory and can only
1357 * be scanned by looking in all the container shards.
1359 * @param $storagePath string
1360 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1362 final protected function resolveStoragePath( $storagePath ) {
1363 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1364 if ( $backend === $this->name
) { // must be for this backend
1365 $relPath = self
::normalizeContainerPath( $relPath );
1366 if ( $relPath !== null ) {
1367 // Get shard for the normalized path if this container is sharded
1368 $cShard = $this->getContainerShard( $container, $relPath );
1369 // Validate and sanitize the relative path (backend-specific)
1370 $relPath = $this->resolveContainerPath( $container, $relPath );
1371 if ( $relPath !== null ) {
1372 // Prepend any wiki ID prefix to the container name
1373 $container = $this->fullContainerName( $container );
1374 if ( self
::isValidContainerName( $container ) ) {
1375 // Validate and sanitize the container name (backend-specific)
1376 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1377 if ( $container !== null ) {
1378 return array( $container, $relPath, $cShard );
1384 return array( null, null, null );
1388 * Like resolveStoragePath() except null values are returned if
1389 * the container is sharded and the shard could not be determined.
1391 * @see FileBackendStore::resolveStoragePath()
1393 * @param $storagePath string
1394 * @return Array (container, path) or (null, null) if invalid
1396 final protected function resolveStoragePathReal( $storagePath ) {
1397 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1398 if ( $cShard !== null ) {
1399 return array( $container, $relPath );
1401 return array( null, null );
1405 * Get the container name shard suffix for a given path.
1406 * Any empty suffix means the container is not sharded.
1408 * @param $container string Container name
1409 * @param $relPath string Storage path relative to the container
1410 * @return string|null Returns null if shard could not be determined
1412 final protected function getContainerShard( $container, $relPath ) {
1413 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1414 if ( $levels == 1 ||
$levels == 2 ) {
1415 // Hash characters are either base 16 or 36
1416 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1417 // Get a regex that represents the shard portion of paths.
1418 // The concatenation of the captures gives us the shard.
1419 if ( $levels === 1 ) { // 16 or 36 shards per container
1420 $hashDirRegex = '(' . $char . ')';
1421 } else { // 256 or 1296 shards per container
1422 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1423 $hashDirRegex = $char . '/(' . $char . '{2})';
1424 } else { // short hash dir format (e.g. "a/b/c")
1425 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1428 // Allow certain directories to be above the hash dirs so as
1429 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1430 // They must be 2+ chars to avoid any hash directory ambiguity.
1432 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1433 return '.' . implode( '', array_slice( $m, 1 ) );
1435 return null; // failed to match
1437 return ''; // no sharding
1441 * Check if a storage path maps to a single shard.
1442 * Container dirs like "a", where the container shards on "x/xy",
1443 * can reside on several shards. Such paths are tricky to handle.
1445 * @param $storagePath string Storage path
1448 final public function isSingleShardPathInternal( $storagePath ) {
1449 list( $c, $r, $shard ) = $this->resolveStoragePath( $storagePath );
1450 return ( $shard !== null );
1454 * Get the sharding config for a container.
1455 * If greater than 0, then all file storage paths within
1456 * the container are required to be hashed accordingly.
1458 * @param $container string
1459 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
1461 final protected function getContainerHashLevels( $container ) {
1462 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1463 $config = $this->shardViaHashLevels
[$container];
1464 $hashLevels = (int)$config['levels'];
1465 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1466 $hashBase = (int)$config['base'];
1467 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1468 return array( $hashLevels, $hashBase, $config['repeat'] );
1472 return array( 0, 0, false ); // no sharding
1476 * Get a list of full container shard suffixes for a container
1478 * @param $container string
1481 final protected function getContainerSuffixes( $container ) {
1483 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1484 if ( $digits > 0 ) {
1485 $numShards = pow( $base, $digits );
1486 for ( $index = 0; $index < $numShards; $index++
) {
1487 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1494 * Get the full container name, including the wiki ID prefix
1496 * @param $container string
1499 final protected function fullContainerName( $container ) {
1500 if ( $this->wikiId
!= '' ) {
1501 return "{$this->wikiId}-$container";
1508 * Resolve a container name, checking if it's allowed by the backend.
1509 * This is intended for internal use, such as encoding illegal chars.
1510 * Subclasses can override this to be more restrictive.
1512 * @param $container string
1513 * @return string|null
1515 protected function resolveContainerName( $container ) {
1520 * Resolve a relative storage path, checking if it's allowed by the backend.
1521 * This is intended for internal use, such as encoding illegal chars or perhaps
1522 * getting absolute paths (e.g. FS based backends). Note that the relative path
1523 * may be the empty string (e.g. the path is simply to the container).
1525 * @param $container string Container name
1526 * @param $relStoragePath string Storage path relative to the container
1527 * @return string|null Path or null if not valid
1529 protected function resolveContainerPath( $container, $relStoragePath ) {
1530 return $relStoragePath;
1534 * Get the cache key for a container
1536 * @param $container string Resolved container name
1539 private function containerCacheKey( $container ) {
1540 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1544 * Set the cached info for a container
1546 * @param $container string Resolved container name
1547 * @param $val mixed Information to cache
1549 final protected function setContainerCache( $container, $val ) {
1550 $this->memCache
->add( $this->containerCacheKey( $container ), $val, 14*86400 );
1554 * Delete the cached info for a container.
1555 * The cache key is salted for a while to prevent race conditions.
1557 * @param $container string Resolved container name
1559 final protected function deleteContainerCache( $container ) {
1560 if ( !$this->memCache
->set( $this->containerCacheKey( $container ), 'PURGED', 300 ) ) {
1561 trigger_error( "Unable to delete stat cache for container $container." );
1566 * Do a batch lookup from cache for container stats for all containers
1567 * used in a list of container names, storage paths, or FileOp objects.
1568 * This loads the persistent cache values into the process cache.
1570 * @param $items Array
1573 final protected function primeContainerCache( array $items ) {
1574 wfProfileIn( __METHOD__
);
1575 wfProfileIn( __METHOD__
. '-' . $this->name
);
1577 $paths = array(); // list of storage paths
1578 $contNames = array(); // (cache key => resolved container name)
1579 // Get all the paths/containers from the items...
1580 foreach ( $items as $item ) {
1581 if ( $item instanceof FileOp
) {
1582 $paths = array_merge( $paths, $item->storagePathsRead() );
1583 $paths = array_merge( $paths, $item->storagePathsChanged() );
1584 } elseif ( self
::isStoragePath( $item ) ) {
1586 } elseif ( is_string( $item ) ) { // full container name
1587 $contNames[$this->containerCacheKey( $item )] = $item;
1590 // Get all the corresponding cache keys for paths...
1591 foreach ( $paths as $path ) {
1592 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1593 if ( $fullCont !== null ) { // valid path for this backend
1594 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1598 $contInfo = array(); // (resolved container name => cache value)
1599 // Get all cache entries for these container cache keys...
1600 $values = $this->memCache
->getMulti( array_keys( $contNames ) );
1601 foreach ( $values as $cacheKey => $val ) {
1602 $contInfo[$contNames[$cacheKey]] = $val;
1605 // Populate the container process cache for the backend...
1606 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1608 wfProfileOut( __METHOD__
. '-' . $this->name
);
1609 wfProfileOut( __METHOD__
);
1613 * Fill the backend-specific process cache given an array of
1614 * resolved container names and their corresponding cached info.
1615 * Only containers that actually exist should appear in the map.
1617 * @param $containerInfo Array Map of resolved container names to cached info
1620 protected function doPrimeContainerCache( array $containerInfo ) {}
1623 * Get the cache key for a file path
1625 * @param $path string Normalized storage path
1628 private function fileCacheKey( $path ) {
1629 return wfMemcKey( 'backend', $this->getName(), 'file', sha1( $path ) );
1633 * Set the cached stat info for a file path.
1634 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1635 * salting for the case when a file is created at a path were there was none before.
1637 * @param $path string Storage path
1638 * @param $val mixed Information to cache
1640 final protected function setFileCache( $path, $val ) {
1641 $path = FileBackend
::normalizeStoragePath( $path );
1642 if ( $path === null ) {
1643 return; // invalid storage path
1645 $this->memCache
->add( $this->fileCacheKey( $path ), $val, 7*86400 );
1649 * Delete the cached stat info for a file path.
1650 * The cache key is salted for a while to prevent race conditions.
1652 * @param $path string Storage path
1654 final protected function deleteFileCache( $path ) {
1655 $path = FileBackend
::normalizeStoragePath( $path );
1656 if ( $path === null ) {
1657 return; // invalid storage path
1659 if ( !$this->memCache
->set( $this->fileCacheKey( $path ), 'PURGED', 300 ) ) {
1660 trigger_error( "Unable to delete stat cache for file $path." );
1665 * Do a batch lookup from cache for file stats for all paths
1666 * used in a list of storage paths or FileOp objects.
1667 * This loads the persistent cache values into the process cache.
1669 * @param $items Array List of storage paths or FileOps
1672 final protected function primeFileCache( array $items ) {
1673 wfProfileIn( __METHOD__
);
1674 wfProfileIn( __METHOD__
. '-' . $this->name
);
1676 $paths = array(); // list of storage paths
1677 $pathNames = array(); // (cache key => storage path)
1678 // Get all the paths/containers from the items...
1679 foreach ( $items as $item ) {
1680 if ( $item instanceof FileOp
) {
1681 $paths = array_merge( $paths, $item->storagePathsRead() );
1682 $paths = array_merge( $paths, $item->storagePathsChanged() );
1683 } elseif ( self
::isStoragePath( $item ) ) {
1684 $paths[] = FileBackend
::normalizeStoragePath( $item );
1687 // Get rid of any paths that failed normalization...
1688 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1689 // Get all the corresponding cache keys for paths...
1690 foreach ( $paths as $path ) {
1691 list( $cont, $rel, $s ) = $this->resolveStoragePath( $path );
1692 if ( $rel !== null ) { // valid path for this backend
1693 $pathNames[$this->fileCacheKey( $path )] = $path;
1696 // Get all cache entries for these container cache keys...
1697 $values = $this->memCache
->getMulti( array_keys( $pathNames ) );
1698 foreach ( $values as $cacheKey => $val ) {
1699 if ( is_array( $val ) ) {
1700 $path = $pathNames[$cacheKey];
1701 $this->cheapCache
->set( $path, 'stat', $val );
1702 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1703 $this->cheapCache
->set( $path, 'sha1',
1704 array( 'hash' => $val['sha1'], 'latest' => $val['latest'] ) );
1709 wfProfileOut( __METHOD__
. '-' . $this->name
);
1710 wfProfileOut( __METHOD__
);
1714 * Set the 'concurrency' option from a list of operation options
1716 * @param $opts array Map of operation options
1719 final protected function setConcurrencyFlags( array $opts ) {
1720 $opts['concurrency'] = 1; // off
1721 if ( $this->parallelize
=== 'implicit' ) {
1722 if ( !isset( $opts['parallelize'] ) ||
$opts['parallelize'] ) {
1723 $opts['concurrency'] = $this->concurrency
;
1725 } elseif ( $this->parallelize
=== 'explicit' ) {
1726 if ( !empty( $opts['parallelize'] ) ) {
1727 $opts['concurrency'] = $this->concurrency
;
1735 * FileBackendStore helper class for performing asynchronous file operations.
1737 * For example, calling FileBackendStore::createInternal() with the "async"
1738 * param flag may result in a Status that contains this object as a value.
1739 * This class is largely backend-specific and is mostly just "magic" to be
1740 * passed to FileBackendStore::executeOpHandlesInternal().
1742 abstract class FileBackendStoreOpHandle
{
1744 public $params = array(); // params to caller functions
1745 /** @var FileBackendStore */
1748 public $resourcesToClose = array();
1750 public $call; // string; name that identifies the function called
1753 * Close all open file handles
1757 public function closeResources() {
1758 array_map( 'fclose', $this->resourcesToClose
);
1763 * FileBackendStore helper function to handle listings that span container shards.
1764 * Do not use this class from places outside of FileBackendStore.
1766 * @ingroup FileBackend
1768 abstract class FileBackendStoreShardListIterator
implements Iterator
{
1769 /** @var FileBackendStore */
1774 protected $shardSuffixes;
1775 protected $container; // string; full container name
1776 protected $directory; // string; resolved relative path
1778 /** @var Traversable */
1780 protected $curShard = 0; // integer
1781 protected $pos = 0; // integer
1784 protected $multiShardPaths = array(); // (rel path => 1)
1787 * @param $backend FileBackendStore
1788 * @param $container string Full storage container name
1789 * @param $dir string Storage directory relative to container
1790 * @param $suffixes Array List of container shard suffixes
1791 * @param $params Array
1793 public function __construct(
1794 FileBackendStore
$backend, $container, $dir, array $suffixes, array $params
1796 $this->backend
= $backend;
1797 $this->container
= $container;
1798 $this->directory
= $dir;
1799 $this->shardSuffixes
= $suffixes;
1800 $this->params
= $params;
1804 * @see Iterator::key()
1807 public function key() {
1812 * @see Iterator::valid()
1815 public function valid() {
1816 if ( $this->iter
instanceof Iterator
) {
1817 return $this->iter
->valid();
1818 } elseif ( is_array( $this->iter
) ) {
1819 return ( current( $this->iter
) !== false ); // no paths can have this value
1821 return false; // some failure?
1825 * @see Iterator::current()
1826 * @return string|bool String or false
1828 public function current() {
1829 return ( $this->iter
instanceof Iterator
)
1830 ?
$this->iter
->current()
1831 : current( $this->iter
);
1835 * @see Iterator::next()
1838 public function next() {
1840 ( $this->iter
instanceof Iterator
) ?
$this->iter
->next() : next( $this->iter
);
1842 $continue = false; // keep scanning shards?
1843 $this->filterViaNext(); // filter out duplicates
1844 // Find the next non-empty shard if no elements are left
1845 if ( !$this->valid() ) {
1846 $this->nextShardIteratorIfNotValid();
1847 $continue = $this->valid(); // re-filter unless we ran out of shards
1849 } while ( $continue );
1853 * @see Iterator::rewind()
1856 public function rewind() {
1858 $this->curShard
= 0;
1859 $this->setIteratorFromCurrentShard();
1861 $continue = false; // keep scanning shards?
1862 $this->filterViaNext(); // filter out duplicates
1863 // Find the next non-empty shard if no elements are left
1864 if ( !$this->valid() ) {
1865 $this->nextShardIteratorIfNotValid();
1866 $continue = $this->valid(); // re-filter unless we ran out of shards
1868 } while ( $continue );
1872 * Filter out duplicate items by advancing to the next ones
1874 protected function filterViaNext() {
1875 while ( $this->valid() ) {
1876 $rel = $this->iter
->current(); // path relative to given directory
1877 $path = $this->params
['dir'] . "/{$rel}"; // full storage path
1878 if ( $this->backend
->isSingleShardPathInternal( $path ) ) {
1879 break; // path is only on one shard; no issue with duplicates
1880 } elseif ( isset( $this->multiShardPaths
[$rel] ) ) {
1881 // Don't keep listing paths that are on multiple shards
1882 ( $this->iter
instanceof Iterator
) ?
$this->iter
->next() : next( $this->iter
);
1884 $this->multiShardPaths
[$rel] = 1;
1891 * If the list iterator for this container shard is out of items,
1892 * then move on to the next container that has items.
1893 * If there are none, then it advances to the last container.
1895 protected function nextShardIteratorIfNotValid() {
1896 while ( !$this->valid() && ++
$this->curShard
< count( $this->shardSuffixes
) ) {
1897 $this->setIteratorFromCurrentShard();
1902 * Set the list iterator to that of the current container shard
1904 protected function setIteratorFromCurrentShard() {
1905 $this->iter
= $this->listFromShard(
1906 $this->container
. $this->shardSuffixes
[$this->curShard
],
1907 $this->directory
, $this->params
);
1908 // Start loading results so that current() works
1909 if ( $this->iter
) {
1910 ( $this->iter
instanceof Iterator
) ?
$this->iter
->rewind() : reset( $this->iter
);
1915 * Get the list for a given container shard
1917 * @param $container string Resolved container name
1918 * @param $dir string Resolved path relative to container
1919 * @param $params Array
1920 * @return Traversable|Array|null
1922 abstract protected function listFromShard( $container, $dir, array $params );
1926 * Iterator for listing directories
1928 class FileBackendStoreShardDirIterator
extends FileBackendStoreShardListIterator
{
1930 * @see FileBackendStoreShardListIterator::listFromShard()
1931 * @return Array|null|Traversable
1933 protected function listFromShard( $container, $dir, array $params ) {
1934 return $this->backend
->getDirectoryListInternal( $container, $dir, $params );
1939 * Iterator for listing regular files
1941 class FileBackendStoreShardFileIterator
extends FileBackendStoreShardListIterator
{
1943 * @see FileBackendStoreShardListIterator::listFromShard()
1944 * @return Array|null|Traversable
1946 protected function listFromShard( $container, $dir, array $params ) {
1947 return $this->backend
->getFileListInternal( $container, $dir, $params );