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)
52 * @see FileBackend::__construct()
54 * @param $config Array
56 public function __construct( array $config ) {
57 parent
::__construct( $config );
58 $this->memCache
= new EmptyBagOStuff(); // disabled by default
59 $this->cheapCache
= new ProcessCacheLRU( 300 );
60 $this->expensiveCache
= new ProcessCacheLRU( 5 );
64 * Get the maximum allowable file size given backend
65 * medium restrictions and basic performance constraints.
66 * Do not call this function from places outside FileBackend and FileOp.
68 * @return integer Bytes
70 final public function maxFileSizeInternal() {
71 return $this->maxFileSize
;
75 * Check if a file can be created at a given storage path.
76 * FS backends should check if the parent directory exists and the file is writable.
77 * Backends using key/value stores should check if the container exists.
79 * @param $storagePath string
82 abstract public function isPathUsableInternal( $storagePath );
85 * Create a file in the backend with the given contents.
86 * This will overwrite any file that exists at the destination.
87 * Do not call this function from places outside FileBackend and FileOp.
90 * - content : the raw file contents
91 * - dst : destination storage path
92 * - disposition : Content-Disposition header value for the destination
93 * - async : Status will be returned immediately if supported.
94 * If the status is OK, then its value field will be
95 * set to a FileBackendStoreOpHandle object.
97 * @param $params Array
100 final public function createInternal( array $params ) {
101 wfProfileIn( __METHOD__
);
102 wfProfileIn( __METHOD__
. '-' . $this->name
);
103 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
104 $status = Status
::newFatal( 'backend-fail-maxsize',
105 $params['dst'], $this->maxFileSizeInternal() );
107 $status = $this->doCreateInternal( $params );
108 $this->clearCache( array( $params['dst'] ) );
109 $this->deleteFileCache( $params['dst'] ); // persistent cache
111 wfProfileOut( __METHOD__
. '-' . $this->name
);
112 wfProfileOut( __METHOD__
);
117 * @see FileBackendStore::createInternal()
119 abstract protected function doCreateInternal( array $params );
122 * Store a file into the backend from a file on disk.
123 * This will overwrite any file that exists at the destination.
124 * Do not call this function from places outside FileBackend and FileOp.
127 * - src : source path on disk
128 * - dst : destination storage path
129 * - disposition : Content-Disposition header value for the destination
130 * - async : Status will be returned immediately if supported.
131 * If the status is OK, then its value field will be
132 * set to a FileBackendStoreOpHandle object.
134 * @param $params Array
137 final public function storeInternal( array $params ) {
138 wfProfileIn( __METHOD__
);
139 wfProfileIn( __METHOD__
. '-' . $this->name
);
140 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
141 $status = Status
::newFatal( 'backend-fail-maxsize',
142 $params['dst'], $this->maxFileSizeInternal() );
144 $status = $this->doStoreInternal( $params );
145 $this->clearCache( array( $params['dst'] ) );
146 $this->deleteFileCache( $params['dst'] ); // persistent cache
148 wfProfileOut( __METHOD__
. '-' . $this->name
);
149 wfProfileOut( __METHOD__
);
154 * @see FileBackendStore::storeInternal()
156 abstract protected function doStoreInternal( array $params );
159 * Copy a file from one storage path to another in the backend.
160 * This will overwrite any file that exists at the destination.
161 * Do not call this function from places outside FileBackend and FileOp.
164 * - src : source storage path
165 * - dst : destination storage path
166 * - ignoreMissingSource : do nothing if the source file does not exist
167 * - disposition : Content-Disposition header value for the destination
168 * - async : Status will be returned immediately if supported.
169 * If the status is OK, then its value field will be
170 * set to a FileBackendStoreOpHandle object.
172 * @param $params Array
175 final public function copyInternal( array $params ) {
176 wfProfileIn( __METHOD__
);
177 wfProfileIn( __METHOD__
. '-' . $this->name
);
178 $status = $this->doCopyInternal( $params );
179 $this->clearCache( array( $params['dst'] ) );
180 $this->deleteFileCache( $params['dst'] ); // persistent cache
181 wfProfileOut( __METHOD__
. '-' . $this->name
);
182 wfProfileOut( __METHOD__
);
187 * @see FileBackendStore::copyInternal()
189 abstract protected function doCopyInternal( array $params );
192 * Delete a file at the storage path.
193 * Do not call this function from places outside FileBackend and FileOp.
196 * - src : source storage path
197 * - ignoreMissingSource : do nothing if the source file does not exist
198 * - async : Status will be returned immediately if supported.
199 * If the status is OK, then its value field will be
200 * set to a FileBackendStoreOpHandle object.
202 * @param $params Array
205 final public function deleteInternal( array $params ) {
206 wfProfileIn( __METHOD__
);
207 wfProfileIn( __METHOD__
. '-' . $this->name
);
208 $status = $this->doDeleteInternal( $params );
209 $this->clearCache( array( $params['src'] ) );
210 $this->deleteFileCache( $params['src'] ); // persistent cache
211 wfProfileOut( __METHOD__
. '-' . $this->name
);
212 wfProfileOut( __METHOD__
);
217 * @see FileBackendStore::deleteInternal()
219 abstract protected function doDeleteInternal( array $params );
222 * Move a file from one storage path to another in the backend.
223 * This will overwrite any file that exists at the destination.
224 * Do not call this function from places outside FileBackend and FileOp.
227 * - src : source storage path
228 * - dst : destination storage path
229 * - ignoreMissingSource : do nothing if the source file does not exist
230 * - disposition : Content-Disposition header value for the destination
231 * - async : Status will be returned immediately if supported.
232 * If the status is OK, then its value field will be
233 * set to a FileBackendStoreOpHandle object.
235 * @param $params Array
238 final public function moveInternal( array $params ) {
239 wfProfileIn( __METHOD__
);
240 wfProfileIn( __METHOD__
. '-' . $this->name
);
241 $status = $this->doMoveInternal( $params );
242 $this->clearCache( array( $params['src'], $params['dst'] ) );
243 $this->deleteFileCache( $params['src'] ); // persistent cache
244 $this->deleteFileCache( $params['dst'] ); // persistent cache
245 wfProfileOut( __METHOD__
. '-' . $this->name
);
246 wfProfileOut( __METHOD__
);
251 * @see FileBackendStore::moveInternal()
254 protected function doMoveInternal( array $params ) {
255 unset( $params['async'] ); // two steps, won't work here :)
256 // Copy source to dest
257 $status = $this->copyInternal( $params );
258 if ( $status->isOK() ) {
259 // Delete source (only fails due to races or medium going down)
260 $status->merge( $this->deleteInternal( array( 'src' => $params['src'] ) ) );
261 $status->setResult( true, $status->value
); // ignore delete() errors
267 * No-op file operation that does nothing.
268 * Do not call this function from places outside FileBackend and FileOp.
270 * @param $params Array
273 final public function nullInternal( array $params ) {
274 return Status
::newGood();
278 * @see FileBackend::concatenate()
281 final public function concatenate( array $params ) {
282 wfProfileIn( __METHOD__
);
283 wfProfileIn( __METHOD__
. '-' . $this->name
);
284 $status = Status
::newGood();
286 // Try to lock the source files for the scope of this function
287 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager
::LOCK_UW
, $status );
288 if ( $status->isOK() ) {
289 // Actually do the file concatenation...
290 $start_time = microtime( true );
291 $status->merge( $this->doConcatenate( $params ) );
292 $sec = microtime( true ) - $start_time;
293 if ( !$status->isOK() ) {
294 wfDebugLog( 'FileOperation', get_class( $this ) . " failed to concatenate " .
295 count( $params['srcs'] ) . " file(s) [$sec sec]" );
299 wfProfileOut( __METHOD__
. '-' . $this->name
);
300 wfProfileOut( __METHOD__
);
305 * @see FileBackendStore::concatenate()
308 protected function doConcatenate( array $params ) {
309 $status = Status
::newGood();
310 $tmpPath = $params['dst']; // convenience
311 unset( $params['latest'] ); // sanity
313 // Check that the specified temp file is valid...
314 wfSuppressWarnings();
315 $ok = ( is_file( $tmpPath ) && filesize( $tmpPath ) == 0 );
317 if ( !$ok ) { // not present or not empty
318 $status->fatal( 'backend-fail-opentemp', $tmpPath );
322 // Get local FS versions of the chunks needed for the concatenation...
323 $fsFiles = $this->getLocalReferenceMulti( $params );
324 foreach ( $fsFiles as $path => &$fsFile ) {
325 if ( !$fsFile ) { // chunk failed to download?
326 $fsFile = $this->getLocalReference( array( 'src' => $path ) );
327 if ( !$fsFile ) { // retry failed?
328 $status->fatal( 'backend-fail-read', $path );
333 unset( $fsFile ); // unset reference so we can reuse $fsFile
335 // Get a handle for the destination temp file
336 $tmpHandle = fopen( $tmpPath, 'ab' );
337 if ( $tmpHandle === false ) {
338 $status->fatal( 'backend-fail-opentemp', $tmpPath );
342 // Build up the temp file using the source chunks (in order)...
343 foreach ( $fsFiles as $virtualSource => $fsFile ) {
344 // Get a handle to the local FS version
345 $sourceHandle = fopen( $fsFile->getPath(), 'rb' );
346 if ( $sourceHandle === false ) {
347 fclose( $tmpHandle );
348 $status->fatal( 'backend-fail-read', $virtualSource );
351 // Append chunk to file (pass chunk size to avoid magic quotes)
352 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
353 fclose( $sourceHandle );
354 fclose( $tmpHandle );
355 $status->fatal( 'backend-fail-writetemp', $tmpPath );
358 fclose( $sourceHandle );
360 if ( !fclose( $tmpHandle ) ) {
361 $status->fatal( 'backend-fail-closetemp', $tmpPath );
365 clearstatcache(); // temp file changed
371 * @see FileBackend::doPrepare()
374 final protected function doPrepare( array $params ) {
375 wfProfileIn( __METHOD__
);
376 wfProfileIn( __METHOD__
. '-' . $this->name
);
378 $status = Status
::newGood();
379 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
380 if ( $dir === null ) {
381 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
382 wfProfileOut( __METHOD__
. '-' . $this->name
);
383 wfProfileOut( __METHOD__
);
384 return $status; // invalid storage path
387 if ( $shard !== null ) { // confined to a single container/shard
388 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
389 } else { // directory is on several shards
390 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
391 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
392 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
393 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
397 wfProfileOut( __METHOD__
. '-' . $this->name
);
398 wfProfileOut( __METHOD__
);
403 * @see FileBackendStore::doPrepare()
406 protected function doPrepareInternal( $container, $dir, array $params ) {
407 return Status
::newGood();
411 * @see FileBackend::doSecure()
414 final protected function doSecure( array $params ) {
415 wfProfileIn( __METHOD__
);
416 wfProfileIn( __METHOD__
. '-' . $this->name
);
417 $status = Status
::newGood();
419 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
420 if ( $dir === null ) {
421 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
422 wfProfileOut( __METHOD__
. '-' . $this->name
);
423 wfProfileOut( __METHOD__
);
424 return $status; // invalid storage path
427 if ( $shard !== null ) { // confined to a single container/shard
428 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
429 } else { // directory is on several shards
430 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
431 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
432 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
433 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
437 wfProfileOut( __METHOD__
. '-' . $this->name
);
438 wfProfileOut( __METHOD__
);
443 * @see FileBackendStore::doSecure()
446 protected function doSecureInternal( $container, $dir, array $params ) {
447 return Status
::newGood();
451 * @see FileBackend::doPublish()
454 final protected function doPublish( array $params ) {
455 wfProfileIn( __METHOD__
);
456 wfProfileIn( __METHOD__
. '-' . $this->name
);
457 $status = Status
::newGood();
459 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
460 if ( $dir === null ) {
461 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
462 wfProfileOut( __METHOD__
. '-' . $this->name
);
463 wfProfileOut( __METHOD__
);
464 return $status; // invalid storage path
467 if ( $shard !== null ) { // confined to a single container/shard
468 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
469 } else { // directory is on several shards
470 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
471 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
472 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
473 $status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
477 wfProfileOut( __METHOD__
. '-' . $this->name
);
478 wfProfileOut( __METHOD__
);
483 * @see FileBackendStore::doPublish()
486 protected function doPublishInternal( $container, $dir, array $params ) {
487 return Status
::newGood();
491 * @see FileBackend::doClean()
494 final protected function doClean( array $params ) {
495 wfProfileIn( __METHOD__
);
496 wfProfileIn( __METHOD__
. '-' . $this->name
);
497 $status = Status
::newGood();
499 // Recursive: first delete all empty subdirs recursively
500 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
501 $subDirsRel = $this->getTopDirectoryList( array( 'dir' => $params['dir'] ) );
502 if ( $subDirsRel !== null ) { // no errors
503 foreach ( $subDirsRel as $subDirRel ) {
504 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
505 $status->merge( $this->doClean( array( 'dir' => $subDir ) +
$params ) );
510 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
511 if ( $dir === null ) {
512 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
513 wfProfileOut( __METHOD__
. '-' . $this->name
);
514 wfProfileOut( __METHOD__
);
515 return $status; // invalid storage path
518 // Attempt to lock this directory...
519 $filesLockEx = array( $params['dir'] );
520 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
521 if ( !$status->isOK() ) {
522 wfProfileOut( __METHOD__
. '-' . $this->name
);
523 wfProfileOut( __METHOD__
);
524 return $status; // abort
527 if ( $shard !== null ) { // confined to a single container/shard
528 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
529 $this->deleteContainerCache( $fullCont ); // purge cache
530 } else { // directory is on several shards
531 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
532 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
533 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
534 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
535 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
539 wfProfileOut( __METHOD__
. '-' . $this->name
);
540 wfProfileOut( __METHOD__
);
545 * @see FileBackendStore::doClean()
548 protected function doCleanInternal( $container, $dir, array $params ) {
549 return Status
::newGood();
553 * @see FileBackend::fileExists()
556 final public function fileExists( array $params ) {
557 wfProfileIn( __METHOD__
);
558 wfProfileIn( __METHOD__
. '-' . $this->name
);
559 $stat = $this->getFileStat( $params );
560 wfProfileOut( __METHOD__
. '-' . $this->name
);
561 wfProfileOut( __METHOD__
);
562 return ( $stat === null ) ?
null : (bool)$stat; // null => failure
566 * @see FileBackend::getFileTimestamp()
569 final public function getFileTimestamp( array $params ) {
570 wfProfileIn( __METHOD__
);
571 wfProfileIn( __METHOD__
. '-' . $this->name
);
572 $stat = $this->getFileStat( $params );
573 wfProfileOut( __METHOD__
. '-' . $this->name
);
574 wfProfileOut( __METHOD__
);
575 return $stat ?
$stat['mtime'] : false;
579 * @see FileBackend::getFileSize()
582 final public function getFileSize( array $params ) {
583 wfProfileIn( __METHOD__
);
584 wfProfileIn( __METHOD__
. '-' . $this->name
);
585 $stat = $this->getFileStat( $params );
586 wfProfileOut( __METHOD__
. '-' . $this->name
);
587 wfProfileOut( __METHOD__
);
588 return $stat ?
$stat['size'] : false;
592 * @see FileBackend::getFileStat()
595 final public function getFileStat( array $params ) {
596 $path = self
::normalizeStoragePath( $params['src'] );
597 if ( $path === null ) {
598 return false; // invalid storage path
600 wfProfileIn( __METHOD__
);
601 wfProfileIn( __METHOD__
. '-' . $this->name
);
602 $latest = !empty( $params['latest'] ); // use latest data?
603 if ( !$this->cheapCache
->has( $path, 'stat' ) ) {
604 $this->primeFileCache( array( $path ) ); // check persistent cache
606 if ( $this->cheapCache
->has( $path, 'stat' ) ) {
607 $stat = $this->cheapCache
->get( $path, 'stat' );
608 // If we want the latest data, check that this cached
609 // value was in fact fetched with the latest available data.
610 if ( !$latest ||
$stat['latest'] ) {
611 wfProfileOut( __METHOD__
. '-' . $this->name
);
612 wfProfileOut( __METHOD__
);
616 wfProfileIn( __METHOD__
. '-miss' );
617 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
618 $stat = $this->doGetFileStat( $params );
619 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
620 wfProfileOut( __METHOD__
. '-miss' );
621 if ( is_array( $stat ) ) { // don't cache negatives
622 $stat['latest'] = $latest;
623 $this->cheapCache
->set( $path, 'stat', $stat );
624 $this->setFileCache( $path, $stat ); // update persistent cache
625 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
626 $this->cheapCache
->set( $path, 'sha1',
627 array( 'hash' => $stat['sha1'], 'latest' => $latest ) );
630 wfDebug( __METHOD__
. ": File $path does not exist.\n" );
632 wfProfileOut( __METHOD__
. '-' . $this->name
);
633 wfProfileOut( __METHOD__
);
638 * @see FileBackendStore::getFileStat()
640 abstract protected function doGetFileStat( array $params );
643 * @see FileBackend::getFileContentsMulti()
646 public function getFileContentsMulti( array $params ) {
647 wfProfileIn( __METHOD__
);
648 wfProfileIn( __METHOD__
. '-' . $this->name
);
650 $params = $this->setConcurrencyFlags( $params );
651 $contents = $this->doGetFileContentsMulti( $params );
653 wfProfileOut( __METHOD__
. '-' . $this->name
);
654 wfProfileOut( __METHOD__
);
659 * @see FileBackendStore::getFileContentsMulti()
662 protected function doGetFileContentsMulti( array $params ) {
664 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
665 wfSuppressWarnings();
666 $contents[$path] = $fsFile ?
file_get_contents( $fsFile->getPath() ) : false;
673 * @see FileBackend::getFileSha1Base36()
674 * @return bool|string
676 final public function getFileSha1Base36( array $params ) {
677 $path = self
::normalizeStoragePath( $params['src'] );
678 if ( $path === null ) {
679 return false; // invalid storage path
681 wfProfileIn( __METHOD__
);
682 wfProfileIn( __METHOD__
. '-' . $this->name
);
683 $latest = !empty( $params['latest'] ); // use latest data?
684 if ( $this->cheapCache
->has( $path, 'sha1' ) ) {
685 $stat = $this->cheapCache
->get( $path, 'sha1' );
686 // If we want the latest data, check that this cached
687 // value was in fact fetched with the latest available data.
688 if ( !$latest ||
$stat['latest'] ) {
689 wfProfileOut( __METHOD__
. '-' . $this->name
);
690 wfProfileOut( __METHOD__
);
691 return $stat['hash'];
694 wfProfileIn( __METHOD__
. '-miss' );
695 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
696 $hash = $this->doGetFileSha1Base36( $params );
697 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
698 wfProfileOut( __METHOD__
. '-miss' );
699 if ( $hash ) { // don't cache negatives
700 $this->cheapCache
->set( $path, 'sha1',
701 array( 'hash' => $hash, 'latest' => $latest ) );
703 wfProfileOut( __METHOD__
. '-' . $this->name
);
704 wfProfileOut( __METHOD__
);
709 * @see FileBackendStore::getFileSha1Base36()
710 * @return bool|string
712 protected function doGetFileSha1Base36( array $params ) {
713 $fsFile = $this->getLocalReference( $params );
717 return $fsFile->getSha1Base36();
722 * @see FileBackend::getFileProps()
725 final public function getFileProps( array $params ) {
726 wfProfileIn( __METHOD__
);
727 wfProfileIn( __METHOD__
. '-' . $this->name
);
728 $fsFile = $this->getLocalReference( $params );
729 $props = $fsFile ?
$fsFile->getProps() : FSFile
::placeholderProps();
730 wfProfileOut( __METHOD__
. '-' . $this->name
);
731 wfProfileOut( __METHOD__
);
736 * @see FileBackend::getLocalReferenceMulti()
739 final public function getLocalReferenceMulti( array $params ) {
740 wfProfileIn( __METHOD__
);
741 wfProfileIn( __METHOD__
. '-' . $this->name
);
743 $params = $this->setConcurrencyFlags( $params );
745 $fsFiles = array(); // (path => FSFile)
746 $latest = !empty( $params['latest'] ); // use latest data?
747 // Reuse any files already in process cache...
748 foreach ( $params['srcs'] as $src ) {
749 $path = self
::normalizeStoragePath( $src );
750 if ( $path === null ) {
751 $fsFiles[$src] = null; // invalid storage path
752 } elseif ( $this->expensiveCache
->has( $path, 'localRef' ) ) {
753 $val = $this->expensiveCache
->get( $path, 'localRef' );
754 // If we want the latest data, check that this cached
755 // value was in fact fetched with the latest available data.
756 if ( !$latest ||
$val['latest'] ) {
757 $fsFiles[$src] = $val['object'];
761 // Fetch local references of any remaning files...
762 $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
763 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
764 $fsFiles[$path] = $fsFile;
765 if ( $fsFile ) { // update the process cache...
766 $this->expensiveCache
->set( $path, 'localRef',
767 array( 'object' => $fsFile, 'latest' => $latest ) );
771 wfProfileOut( __METHOD__
. '-' . $this->name
);
772 wfProfileOut( __METHOD__
);
777 * @see FileBackendStore::getLocalReferenceMulti()
780 protected function doGetLocalReferenceMulti( array $params ) {
781 return $this->doGetLocalCopyMulti( $params );
785 * @see FileBackend::getLocalCopyMulti()
788 final public function getLocalCopyMulti( array $params ) {
789 wfProfileIn( __METHOD__
);
790 wfProfileIn( __METHOD__
. '-' . $this->name
);
792 $params = $this->setConcurrencyFlags( $params );
793 $tmpFiles = $this->doGetLocalCopyMulti( $params );
795 wfProfileOut( __METHOD__
. '-' . $this->name
);
796 wfProfileOut( __METHOD__
);
801 * @see FileBackendStore::getLocalCopyMulti()
804 abstract protected function doGetLocalCopyMulti( array $params );
807 * @see FileBackend::streamFile()
810 final public function streamFile( array $params ) {
811 wfProfileIn( __METHOD__
);
812 wfProfileIn( __METHOD__
. '-' . $this->name
);
813 $status = Status
::newGood();
815 $info = $this->getFileStat( $params );
816 if ( !$info ) { // let StreamFile handle the 404
817 $status->fatal( 'backend-fail-notexists', $params['src'] );
820 // Set output buffer and HTTP headers for stream
821 $extraHeaders = isset( $params['headers'] ) ?
$params['headers'] : array();
822 $res = StreamFile
::prepareForStream( $params['src'], $info, $extraHeaders );
823 if ( $res == StreamFile
::NOT_MODIFIED
) {
824 // do nothing; client cache is up to date
825 } elseif ( $res == StreamFile
::READY_STREAM
) {
826 wfProfileIn( __METHOD__
. '-send' );
827 wfProfileIn( __METHOD__
. '-send-' . $this->name
);
828 $status = $this->doStreamFile( $params );
829 wfProfileOut( __METHOD__
. '-send-' . $this->name
);
830 wfProfileOut( __METHOD__
. '-send' );
831 if ( !$status->isOK() ) {
832 // Per bug 41113, nasty things can happen if bad cache entries get
833 // stuck in cache. It's also possible that this error can come up
834 // with simple race conditions. Clear out the stat cache to be safe.
835 $this->clearCache( array( $params['src'] ) );
836 $this->deleteFileCache( $params['src'] );
837 trigger_error( "Bad stat cache or race condition for file {$params['src']}." );
840 $status->fatal( 'backend-fail-stream', $params['src'] );
843 wfProfileOut( __METHOD__
. '-' . $this->name
);
844 wfProfileOut( __METHOD__
);
849 * @see FileBackendStore::streamFile()
852 protected function doStreamFile( array $params ) {
853 $status = Status
::newGood();
855 $fsFile = $this->getLocalReference( $params );
857 $status->fatal( 'backend-fail-stream', $params['src'] );
858 } elseif ( !readfile( $fsFile->getPath() ) ) {
859 $status->fatal( 'backend-fail-stream', $params['src'] );
866 * @see FileBackend::directoryExists()
869 final public function directoryExists( array $params ) {
870 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
871 if ( $dir === null ) {
872 return false; // invalid storage path
874 if ( $shard !== null ) { // confined to a single container/shard
875 return $this->doDirectoryExists( $fullCont, $dir, $params );
876 } else { // directory is on several shards
877 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
878 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
879 $res = false; // response
880 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
881 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
885 } elseif ( $exists === null ) { // error?
886 $res = null; // if we don't find anything, it is indeterminate
894 * @see FileBackendStore::directoryExists()
896 * @param $container string Resolved container name
897 * @param $dir string Resolved path relative to container
898 * @param $params Array
901 abstract protected function doDirectoryExists( $container, $dir, array $params );
904 * @see FileBackend::getDirectoryList()
905 * @return Traversable|Array|null Returns null on failure
907 final public function getDirectoryList( array $params ) {
908 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
909 if ( $dir === null ) { // invalid storage path
912 if ( $shard !== null ) {
913 // File listing is confined to a single container/shard
914 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
916 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
917 // File listing spans multiple containers/shards
918 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
919 return new FileBackendStoreShardDirIterator( $this,
920 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
925 * Do not call this function from places outside FileBackend
927 * @see FileBackendStore::getDirectoryList()
929 * @param $container string Resolved container name
930 * @param $dir string Resolved path relative to container
931 * @param $params Array
932 * @return Traversable|Array|null Returns null on failure
934 abstract public function getDirectoryListInternal( $container, $dir, array $params );
937 * @see FileBackend::getFileList()
938 * @return Traversable|Array|null Returns null on failure
940 final public function getFileList( array $params ) {
941 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
942 if ( $dir === null ) { // invalid storage path
945 if ( $shard !== null ) {
946 // File listing is confined to a single container/shard
947 return $this->getFileListInternal( $fullCont, $dir, $params );
949 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
950 // File listing spans multiple containers/shards
951 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
952 return new FileBackendStoreShardFileIterator( $this,
953 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
958 * Do not call this function from places outside FileBackend
960 * @see FileBackendStore::getFileList()
962 * @param $container string Resolved container name
963 * @param $dir string Resolved path relative to container
964 * @param $params Array
965 * @return Traversable|Array|null Returns null on failure
967 abstract public function getFileListInternal( $container, $dir, array $params );
970 * Return a list of FileOp objects from a list of operations.
971 * Do not call this function from places outside FileBackend.
973 * The result must have the same number of items as the input.
974 * An exception is thrown if an unsupported operation is requested.
976 * @param $ops Array Same format as doOperations()
977 * @return Array List of FileOp objects
978 * @throws MWException
980 final public function getOperationsInternal( array $ops ) {
981 $supportedOps = array(
982 'store' => 'StoreFileOp',
983 'copy' => 'CopyFileOp',
984 'move' => 'MoveFileOp',
985 'delete' => 'DeleteFileOp',
986 'create' => 'CreateFileOp',
987 'null' => 'NullFileOp'
990 $performOps = array(); // array of FileOp objects
991 // Build up ordered array of FileOps...
992 foreach ( $ops as $operation ) {
993 $opName = $operation['op'];
994 if ( isset( $supportedOps[$opName] ) ) {
995 $class = $supportedOps[$opName];
996 // Get params for this operation
997 $params = $operation;
998 // Append the FileOp class
999 $performOps[] = new $class( $this, $params );
1001 throw new MWException( "Operation '$opName' is not supported." );
1009 * Get a list of storage paths to lock for a list of operations
1010 * Returns an array with 'sh' (shared) and 'ex' (exclusive) keys,
1011 * each corresponding to a list of storage paths to be locked.
1012 * All returned paths are normalized.
1014 * @param $performOps Array List of FileOp objects
1015 * @return Array ('sh' => list of paths, 'ex' => list of paths)
1017 final public function getPathsToLockForOpsInternal( array $performOps ) {
1018 // Build up a list of files to lock...
1019 $paths = array( 'sh' => array(), 'ex' => array() );
1020 foreach ( $performOps as $fileOp ) {
1021 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1022 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1024 // Optimization: if doing an EX lock anyway, don't also set an SH one
1025 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1026 // Get a shared lock on the parent directory of each path changed
1027 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1033 * @see FileBackend::getScopedLocksForOps()
1036 public function getScopedLocksForOps( array $ops, Status
$status ) {
1037 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1039 $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status ),
1040 $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status )
1045 * @see FileBackend::doOperationsInternal()
1048 final protected function doOperationsInternal( array $ops, array $opts ) {
1049 wfProfileIn( __METHOD__
);
1050 wfProfileIn( __METHOD__
. '-' . $this->name
);
1051 $status = Status
::newGood();
1053 // Build up a list of FileOps...
1054 $performOps = $this->getOperationsInternal( $ops );
1056 // Acquire any locks as needed...
1057 if ( empty( $opts['nonLocking'] ) ) {
1058 // Build up a list of files to lock...
1059 $paths = $this->getPathsToLockForOpsInternal( $performOps );
1060 // Try to lock those files for the scope of this function...
1061 $scopeLockS = $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status );
1062 $scopeLockE = $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status );
1063 if ( !$status->isOK() ) {
1064 wfProfileOut( __METHOD__
. '-' . $this->name
);
1065 wfProfileOut( __METHOD__
);
1066 return $status; // abort
1070 // Clear any file cache entries (after locks acquired)
1071 if ( empty( $opts['preserveCache'] ) ) {
1072 $this->clearCache();
1075 // Load from the persistent file and container caches
1076 $this->primeFileCache( $performOps );
1077 $this->primeContainerCache( $performOps );
1079 // Actually attempt the operation batch...
1080 $opts = $this->setConcurrencyFlags( $opts );
1081 $subStatus = FileOpBatch
::attempt( $performOps, $opts, $this->fileJournal
);
1083 // Merge errors into status fields
1084 $status->merge( $subStatus );
1085 $status->success
= $subStatus->success
; // not done in merge()
1087 wfProfileOut( __METHOD__
. '-' . $this->name
);
1088 wfProfileOut( __METHOD__
);
1093 * @see FileBackend::doQuickOperationsInternal()
1095 * @throws MWException
1097 final protected function doQuickOperationsInternal( array $ops ) {
1098 wfProfileIn( __METHOD__
);
1099 wfProfileIn( __METHOD__
. '-' . $this->name
);
1100 $status = Status
::newGood();
1102 $supportedOps = array( 'create', 'store', 'copy', 'move', 'delete', 'null' );
1103 $async = ( $this->parallelize
=== 'implicit' );
1104 $maxConcurrency = $this->concurrency
; // throttle
1106 $statuses = array(); // array of (index => Status)
1107 $fileOpHandles = array(); // list of (index => handle) arrays
1108 $curFileOpHandles = array(); // current handle batch
1109 // Perform the sync-only ops and build up op handles for the async ops...
1110 foreach ( $ops as $index => $params ) {
1111 if ( !in_array( $params['op'], $supportedOps ) ) {
1112 wfProfileOut( __METHOD__
. '-' . $this->name
);
1113 wfProfileOut( __METHOD__
);
1114 throw new MWException( "Operation '{$params['op']}' is not supported." );
1116 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1117 $subStatus = $this->$method( array( 'async' => $async ) +
$params );
1118 if ( $subStatus->value
instanceof FileBackendStoreOpHandle
) { // async
1119 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1120 $fileOpHandles[] = $curFileOpHandles; // push this batch
1121 $curFileOpHandles = array();
1123 $curFileOpHandles[$index] = $subStatus->value
; // keep index
1124 } else { // error or completed
1125 $statuses[$index] = $subStatus; // keep index
1128 if ( count( $curFileOpHandles ) ) {
1129 $fileOpHandles[] = $curFileOpHandles; // last batch
1131 // Do all the async ops that can be done concurrently...
1132 foreach ( $fileOpHandles as $fileHandleBatch ) {
1133 $statuses = $statuses +
$this->executeOpHandlesInternal( $fileHandleBatch );
1135 // Marshall and merge all the responses...
1136 foreach ( $statuses as $index => $subStatus ) {
1137 $status->merge( $subStatus );
1138 if ( $subStatus->isOK() ) {
1139 $status->success
[$index] = true;
1140 ++
$status->successCount
;
1142 $status->success
[$index] = false;
1143 ++
$status->failCount
;
1147 wfProfileOut( __METHOD__
. '-' . $this->name
);
1148 wfProfileOut( __METHOD__
);
1153 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1154 * The resulting Status object fields will correspond
1155 * to the order in which the handles where given.
1157 * @param $handles Array List of FileBackendStoreOpHandle objects
1158 * @return Array Map of Status objects
1159 * @throws MWException
1161 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1162 wfProfileIn( __METHOD__
);
1163 wfProfileIn( __METHOD__
. '-' . $this->name
);
1164 foreach ( $fileOpHandles as $fileOpHandle ) {
1165 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle
) ) {
1166 throw new MWException( "Given a non-FileBackendStoreOpHandle object." );
1167 } elseif ( $fileOpHandle->backend
->getName() !== $this->getName() ) {
1168 throw new MWException( "Given a FileBackendStoreOpHandle for the wrong backend." );
1171 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1172 foreach ( $fileOpHandles as $fileOpHandle ) {
1173 $fileOpHandle->closeResources();
1175 wfProfileOut( __METHOD__
. '-' . $this->name
);
1176 wfProfileOut( __METHOD__
);
1181 * @see FileBackendStore::executeOpHandlesInternal()
1182 * @param array $fileOpHandles
1183 * @throws MWException
1184 * @return Array List of corresponding Status objects
1186 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1187 foreach ( $fileOpHandles as $fileOpHandle ) { // OK if empty
1188 throw new MWException( "This backend supports no asynchronous operations." );
1194 * @see FileBackend::preloadCache()
1196 final public function preloadCache( array $paths ) {
1197 $fullConts = array(); // full container names
1198 foreach ( $paths as $path ) {
1199 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1200 $fullConts[] = $fullCont;
1202 // Load from the persistent file and container caches
1203 $this->primeContainerCache( $fullConts );
1204 $this->primeFileCache( $paths );
1208 * @see FileBackend::clearCache()
1210 final public function clearCache( array $paths = null ) {
1211 if ( is_array( $paths ) ) {
1212 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1213 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1215 if ( $paths === null ) {
1216 $this->cheapCache
->clear();
1217 $this->expensiveCache
->clear();
1219 foreach ( $paths as $path ) {
1220 $this->cheapCache
->clear( $path );
1221 $this->expensiveCache
->clear( $path );
1224 $this->doClearCache( $paths );
1228 * Clears any additional stat caches for storage paths
1230 * @see FileBackend::clearCache()
1232 * @param $paths Array Storage paths (optional)
1235 protected function doClearCache( array $paths = null ) {}
1238 * Is this a key/value store where directories are just virtual?
1239 * Virtual directories exists in so much as files exists that are
1240 * prefixed with the directory path followed by a forward slash.
1244 abstract protected function directoriesAreVirtual();
1247 * Check if a container name is valid.
1248 * This checks for for length and illegal characters.
1250 * @param $container string
1253 final protected static function isValidContainerName( $container ) {
1254 // This accounts for Swift and S3 restrictions while leaving room
1255 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1256 // This disallows directory separators or traversal characters.
1257 // Note that matching strings URL encode to the same string;
1258 // in Swift, the length restriction is *after* URL encoding.
1259 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1263 * Splits a storage path into an internal container name,
1264 * an internal relative file name, and a container shard suffix.
1265 * Any shard suffix is already appended to the internal container name.
1266 * This also checks that the storage path is valid and within this backend.
1268 * If the container is sharded but a suffix could not be determined,
1269 * this means that the path can only refer to a directory and can only
1270 * be scanned by looking in all the container shards.
1272 * @param $storagePath string
1273 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1275 final protected function resolveStoragePath( $storagePath ) {
1276 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1277 if ( $backend === $this->name
) { // must be for this backend
1278 $relPath = self
::normalizeContainerPath( $relPath );
1279 if ( $relPath !== null ) {
1280 // Get shard for the normalized path if this container is sharded
1281 $cShard = $this->getContainerShard( $container, $relPath );
1282 // Validate and sanitize the relative path (backend-specific)
1283 $relPath = $this->resolveContainerPath( $container, $relPath );
1284 if ( $relPath !== null ) {
1285 // Prepend any wiki ID prefix to the container name
1286 $container = $this->fullContainerName( $container );
1287 if ( self
::isValidContainerName( $container ) ) {
1288 // Validate and sanitize the container name (backend-specific)
1289 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1290 if ( $container !== null ) {
1291 return array( $container, $relPath, $cShard );
1297 return array( null, null, null );
1301 * Like resolveStoragePath() except null values are returned if
1302 * the container is sharded and the shard could not be determined.
1304 * @see FileBackendStore::resolveStoragePath()
1306 * @param $storagePath string
1307 * @return Array (container, path) or (null, null) if invalid
1309 final protected function resolveStoragePathReal( $storagePath ) {
1310 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1311 if ( $cShard !== null ) {
1312 return array( $container, $relPath );
1314 return array( null, null );
1318 * Get the container name shard suffix for a given path.
1319 * Any empty suffix means the container is not sharded.
1321 * @param $container string Container name
1322 * @param $relPath string Storage path relative to the container
1323 * @return string|null Returns null if shard could not be determined
1325 final protected function getContainerShard( $container, $relPath ) {
1326 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1327 if ( $levels == 1 ||
$levels == 2 ) {
1328 // Hash characters are either base 16 or 36
1329 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1330 // Get a regex that represents the shard portion of paths.
1331 // The concatenation of the captures gives us the shard.
1332 if ( $levels === 1 ) { // 16 or 36 shards per container
1333 $hashDirRegex = '(' . $char . ')';
1334 } else { // 256 or 1296 shards per container
1335 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1336 $hashDirRegex = $char . '/(' . $char . '{2})';
1337 } else { // short hash dir format (e.g. "a/b/c")
1338 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1341 // Allow certain directories to be above the hash dirs so as
1342 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1343 // They must be 2+ chars to avoid any hash directory ambiguity.
1345 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1346 return '.' . implode( '', array_slice( $m, 1 ) );
1348 return null; // failed to match
1350 return ''; // no sharding
1354 * Check if a storage path maps to a single shard.
1355 * Container dirs like "a", where the container shards on "x/xy",
1356 * can reside on several shards. Such paths are tricky to handle.
1358 * @param $storagePath string Storage path
1361 final public function isSingleShardPathInternal( $storagePath ) {
1362 list( $c, $r, $shard ) = $this->resolveStoragePath( $storagePath );
1363 return ( $shard !== null );
1367 * Get the sharding config for a container.
1368 * If greater than 0, then all file storage paths within
1369 * the container are required to be hashed accordingly.
1371 * @param $container string
1372 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
1374 final protected function getContainerHashLevels( $container ) {
1375 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1376 $config = $this->shardViaHashLevels
[$container];
1377 $hashLevels = (int)$config['levels'];
1378 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1379 $hashBase = (int)$config['base'];
1380 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1381 return array( $hashLevels, $hashBase, $config['repeat'] );
1385 return array( 0, 0, false ); // no sharding
1389 * Get a list of full container shard suffixes for a container
1391 * @param $container string
1394 final protected function getContainerSuffixes( $container ) {
1396 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1397 if ( $digits > 0 ) {
1398 $numShards = pow( $base, $digits );
1399 for ( $index = 0; $index < $numShards; $index++
) {
1400 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1407 * Get the full container name, including the wiki ID prefix
1409 * @param $container string
1412 final protected function fullContainerName( $container ) {
1413 if ( $this->wikiId
!= '' ) {
1414 return "{$this->wikiId}-$container";
1421 * Resolve a container name, checking if it's allowed by the backend.
1422 * This is intended for internal use, such as encoding illegal chars.
1423 * Subclasses can override this to be more restrictive.
1425 * @param $container string
1426 * @return string|null
1428 protected function resolveContainerName( $container ) {
1433 * Resolve a relative storage path, checking if it's allowed by the backend.
1434 * This is intended for internal use, such as encoding illegal chars or perhaps
1435 * getting absolute paths (e.g. FS based backends). Note that the relative path
1436 * may be the empty string (e.g. the path is simply to the container).
1438 * @param $container string Container name
1439 * @param $relStoragePath string Storage path relative to the container
1440 * @return string|null Path or null if not valid
1442 protected function resolveContainerPath( $container, $relStoragePath ) {
1443 return $relStoragePath;
1447 * Get the cache key for a container
1449 * @param $container string Resolved container name
1452 private function containerCacheKey( $container ) {
1453 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1457 * Set the cached info for a container
1459 * @param $container string Resolved container name
1460 * @param $val mixed Information to cache
1462 final protected function setContainerCache( $container, $val ) {
1463 $this->memCache
->add( $this->containerCacheKey( $container ), $val, 14*86400 );
1467 * Delete the cached info for a container.
1468 * The cache key is salted for a while to prevent race conditions.
1470 * @param $container string Resolved container name
1472 final protected function deleteContainerCache( $container ) {
1473 if ( !$this->memCache
->set( $this->containerCacheKey( $container ), 'PURGED', 300 ) ) {
1474 trigger_error( "Unable to delete stat cache for container $container." );
1479 * Do a batch lookup from cache for container stats for all containers
1480 * used in a list of container names, storage paths, or FileOp objects.
1481 * This loads the persistent cache values into the process cache.
1483 * @param $items Array
1486 final protected function primeContainerCache( array $items ) {
1487 wfProfileIn( __METHOD__
);
1488 wfProfileIn( __METHOD__
. '-' . $this->name
);
1490 $paths = array(); // list of storage paths
1491 $contNames = array(); // (cache key => resolved container name)
1492 // Get all the paths/containers from the items...
1493 foreach ( $items as $item ) {
1494 if ( $item instanceof FileOp
) {
1495 $paths = array_merge( $paths, $item->storagePathsRead() );
1496 $paths = array_merge( $paths, $item->storagePathsChanged() );
1497 } elseif ( self
::isStoragePath( $item ) ) {
1499 } elseif ( is_string( $item ) ) { // full container name
1500 $contNames[$this->containerCacheKey( $item )] = $item;
1503 // Get all the corresponding cache keys for paths...
1504 foreach ( $paths as $path ) {
1505 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1506 if ( $fullCont !== null ) { // valid path for this backend
1507 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1511 $contInfo = array(); // (resolved container name => cache value)
1512 // Get all cache entries for these container cache keys...
1513 $values = $this->memCache
->getMulti( array_keys( $contNames ) );
1514 foreach ( $values as $cacheKey => $val ) {
1515 $contInfo[$contNames[$cacheKey]] = $val;
1518 // Populate the container process cache for the backend...
1519 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1521 wfProfileOut( __METHOD__
. '-' . $this->name
);
1522 wfProfileOut( __METHOD__
);
1526 * Fill the backend-specific process cache given an array of
1527 * resolved container names and their corresponding cached info.
1528 * Only containers that actually exist should appear in the map.
1530 * @param $containerInfo Array Map of resolved container names to cached info
1533 protected function doPrimeContainerCache( array $containerInfo ) {}
1536 * Get the cache key for a file path
1538 * @param $path string Normalized storage path
1541 private function fileCacheKey( $path ) {
1542 return wfMemcKey( 'backend', $this->getName(), 'file', sha1( $path ) );
1546 * Set the cached stat info for a file path.
1547 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1548 * salting for the case when a file is created at a path were there was none before.
1550 * @param $path string Storage path
1551 * @param $val mixed Information to cache
1553 final protected function setFileCache( $path, $val ) {
1554 $path = FileBackend
::normalizeStoragePath( $path );
1555 if ( $path === null ) {
1556 return; // invalid storage path
1558 $this->memCache
->add( $this->fileCacheKey( $path ), $val, 7*86400 );
1562 * Delete the cached stat info for a file path.
1563 * The cache key is salted for a while to prevent race conditions.
1565 * @param $path string Storage path
1567 final protected function deleteFileCache( $path ) {
1568 $path = FileBackend
::normalizeStoragePath( $path );
1569 if ( $path === null ) {
1570 return; // invalid storage path
1572 if ( !$this->memCache
->set( $this->fileCacheKey( $path ), 'PURGED', 300 ) ) {
1573 trigger_error( "Unable to delete stat cache for file $path." );
1578 * Do a batch lookup from cache for file stats for all paths
1579 * used in a list of storage paths or FileOp objects.
1580 * This loads the persistent cache values into the process cache.
1582 * @param $items Array List of storage paths or FileOps
1585 final protected function primeFileCache( array $items ) {
1586 wfProfileIn( __METHOD__
);
1587 wfProfileIn( __METHOD__
. '-' . $this->name
);
1589 $paths = array(); // list of storage paths
1590 $pathNames = array(); // (cache key => storage path)
1591 // Get all the paths/containers from the items...
1592 foreach ( $items as $item ) {
1593 if ( $item instanceof FileOp
) {
1594 $paths = array_merge( $paths, $item->storagePathsRead() );
1595 $paths = array_merge( $paths, $item->storagePathsChanged() );
1596 } elseif ( self
::isStoragePath( $item ) ) {
1597 $paths[] = FileBackend
::normalizeStoragePath( $item );
1600 // Get rid of any paths that failed normalization...
1601 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1602 // Get all the corresponding cache keys for paths...
1603 foreach ( $paths as $path ) {
1604 list( $cont, $rel, $s ) = $this->resolveStoragePath( $path );
1605 if ( $rel !== null ) { // valid path for this backend
1606 $pathNames[$this->fileCacheKey( $path )] = $path;
1609 // Get all cache entries for these container cache keys...
1610 $values = $this->memCache
->getMulti( array_keys( $pathNames ) );
1611 foreach ( $values as $cacheKey => $val ) {
1612 if ( is_array( $val ) ) {
1613 $path = $pathNames[$cacheKey];
1614 $this->cheapCache
->set( $path, 'stat', $val );
1615 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1616 $this->cheapCache
->set( $path, 'sha1',
1617 array( 'hash' => $val['sha1'], 'latest' => $val['latest'] ) );
1622 wfProfileOut( __METHOD__
. '-' . $this->name
);
1623 wfProfileOut( __METHOD__
);
1627 * Set the 'concurrency' option from a list of operation options
1629 * @param $opts array Map of operation options
1632 final protected function setConcurrencyFlags( array $opts ) {
1633 $opts['concurrency'] = 1; // off
1634 if ( $this->parallelize
=== 'implicit' ) {
1635 if ( !isset( $opts['parallelize'] ) ||
$opts['parallelize'] ) {
1636 $opts['concurrency'] = $this->concurrency
;
1638 } elseif ( $this->parallelize
=== 'explicit' ) {
1639 if ( !empty( $opts['parallelize'] ) ) {
1640 $opts['concurrency'] = $this->concurrency
;
1648 * FileBackendStore helper class for performing asynchronous file operations.
1650 * For example, calling FileBackendStore::createInternal() with the "async"
1651 * param flag may result in a Status that contains this object as a value.
1652 * This class is largely backend-specific and is mostly just "magic" to be
1653 * passed to FileBackendStore::executeOpHandlesInternal().
1655 abstract class FileBackendStoreOpHandle
{
1657 public $params = array(); // params to caller functions
1658 /** @var FileBackendStore */
1661 public $resourcesToClose = array();
1663 public $call; // string; name that identifies the function called
1666 * Close all open file handles
1670 public function closeResources() {
1671 array_map( 'fclose', $this->resourcesToClose
);
1676 * FileBackendStore helper function to handle listings that span container shards.
1677 * Do not use this class from places outside of FileBackendStore.
1679 * @ingroup FileBackend
1681 abstract class FileBackendStoreShardListIterator
implements Iterator
{
1682 /** @var FileBackendStore */
1687 protected $shardSuffixes;
1688 protected $container; // string; full container name
1689 protected $directory; // string; resolved relative path
1691 /** @var Traversable */
1693 protected $curShard = 0; // integer
1694 protected $pos = 0; // integer
1697 protected $multiShardPaths = array(); // (rel path => 1)
1700 * @param $backend FileBackendStore
1701 * @param $container string Full storage container name
1702 * @param $dir string Storage directory relative to container
1703 * @param $suffixes Array List of container shard suffixes
1704 * @param $params Array
1706 public function __construct(
1707 FileBackendStore
$backend, $container, $dir, array $suffixes, array $params
1709 $this->backend
= $backend;
1710 $this->container
= $container;
1711 $this->directory
= $dir;
1712 $this->shardSuffixes
= $suffixes;
1713 $this->params
= $params;
1717 * @see Iterator::key()
1720 public function key() {
1725 * @see Iterator::valid()
1728 public function valid() {
1729 if ( $this->iter
instanceof Iterator
) {
1730 return $this->iter
->valid();
1731 } elseif ( is_array( $this->iter
) ) {
1732 return ( current( $this->iter
) !== false ); // no paths can have this value
1734 return false; // some failure?
1738 * @see Iterator::current()
1739 * @return string|bool String or false
1741 public function current() {
1742 return ( $this->iter
instanceof Iterator
)
1743 ?
$this->iter
->current()
1744 : current( $this->iter
);
1748 * @see Iterator::next()
1751 public function next() {
1753 ( $this->iter
instanceof Iterator
) ?
$this->iter
->next() : next( $this->iter
);
1755 $continue = false; // keep scanning shards?
1756 $this->filterViaNext(); // filter out duplicates
1757 // Find the next non-empty shard if no elements are left
1758 if ( !$this->valid() ) {
1759 $this->nextShardIteratorIfNotValid();
1760 $continue = $this->valid(); // re-filter unless we ran out of shards
1762 } while ( $continue );
1766 * @see Iterator::rewind()
1769 public function rewind() {
1771 $this->curShard
= 0;
1772 $this->setIteratorFromCurrentShard();
1774 $continue = false; // keep scanning shards?
1775 $this->filterViaNext(); // filter out duplicates
1776 // Find the next non-empty shard if no elements are left
1777 if ( !$this->valid() ) {
1778 $this->nextShardIteratorIfNotValid();
1779 $continue = $this->valid(); // re-filter unless we ran out of shards
1781 } while ( $continue );
1785 * Filter out duplicate items by advancing to the next ones
1787 protected function filterViaNext() {
1788 while ( $this->valid() ) {
1789 $rel = $this->iter
->current(); // path relative to given directory
1790 $path = $this->params
['dir'] . "/{$rel}"; // full storage path
1791 if ( $this->backend
->isSingleShardPathInternal( $path ) ) {
1792 break; // path is only on one shard; no issue with duplicates
1793 } elseif ( isset( $this->multiShardPaths
[$rel] ) ) {
1794 // Don't keep listing paths that are on multiple shards
1795 ( $this->iter
instanceof Iterator
) ?
$this->iter
->next() : next( $this->iter
);
1797 $this->multiShardPaths
[$rel] = 1;
1804 * If the list iterator for this container shard is out of items,
1805 * then move on to the next container that has items.
1806 * If there are none, then it advances to the last container.
1808 protected function nextShardIteratorIfNotValid() {
1809 while ( !$this->valid() && ++
$this->curShard
< count( $this->shardSuffixes
) ) {
1810 $this->setIteratorFromCurrentShard();
1815 * Set the list iterator to that of the current container shard
1817 protected function setIteratorFromCurrentShard() {
1818 $this->iter
= $this->listFromShard(
1819 $this->container
. $this->shardSuffixes
[$this->curShard
],
1820 $this->directory
, $this->params
);
1821 // Start loading results so that current() works
1822 if ( $this->iter
) {
1823 ( $this->iter
instanceof Iterator
) ?
$this->iter
->rewind() : reset( $this->iter
);
1828 * Get the list for a given container shard
1830 * @param $container string Resolved container name
1831 * @param $dir string Resolved path relative to container
1832 * @param $params Array
1833 * @return Traversable|Array|null
1835 abstract protected function listFromShard( $container, $dir, array $params );
1839 * Iterator for listing directories
1841 class FileBackendStoreShardDirIterator
extends FileBackendStoreShardListIterator
{
1843 * @see FileBackendStoreShardListIterator::listFromShard()
1844 * @return Array|null|Traversable
1846 protected function listFromShard( $container, $dir, array $params ) {
1847 return $this->backend
->getDirectoryListInternal( $container, $dir, $params );
1852 * Iterator for listing regular files
1854 class FileBackendStoreShardFileIterator
extends FileBackendStoreShardListIterator
{
1856 * @see FileBackendStoreShardListIterator::listFromShard()
1857 * @return Array|null|Traversable
1859 protected function listFromShard( $container, $dir, array $params ) {
1860 return $this->backend
->getFileListInternal( $container, $dir, $params );