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 * Do not call this function from places outside FileBackend and FileOp.
89 * - content : the raw file contents
90 * - dst : destination storage path
91 * - overwrite : overwrite any file that exists at the destination
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 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
110 $this->deleteFileCache( $params['dst'] ); // persistent cache
113 wfProfileOut( __METHOD__
. '-' . $this->name
);
114 wfProfileOut( __METHOD__
);
119 * @see FileBackendStore::createInternal()
121 abstract protected function doCreateInternal( array $params );
124 * Store a file into the backend from a file on disk.
125 * Do not call this function from places outside FileBackend and FileOp.
128 * - src : source path on disk
129 * - dst : destination storage path
130 * - overwrite : overwrite any file that exists at the destination
131 * - disposition : Content-Disposition header value for the destination
132 * - async : Status will be returned immediately if supported.
133 * If the status is OK, then its value field will be
134 * set to a FileBackendStoreOpHandle object.
136 * @param $params Array
139 final public function storeInternal( array $params ) {
140 wfProfileIn( __METHOD__
);
141 wfProfileIn( __METHOD__
. '-' . $this->name
);
142 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
143 $status = Status
::newFatal( 'backend-fail-maxsize',
144 $params['dst'], $this->maxFileSizeInternal() );
146 $status = $this->doStoreInternal( $params );
147 $this->clearCache( array( $params['dst'] ) );
148 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
149 $this->deleteFileCache( $params['dst'] ); // persistent cache
152 wfProfileOut( __METHOD__
. '-' . $this->name
);
153 wfProfileOut( __METHOD__
);
158 * @see FileBackendStore::storeInternal()
160 abstract protected function doStoreInternal( array $params );
163 * Copy a file from one storage path to another in the backend.
164 * Do not call this function from places outside FileBackend and FileOp.
167 * - src : source storage path
168 * - dst : destination storage path
169 * - overwrite : overwrite any file that exists at the destination
170 * - disposition : Content-Disposition header value for the destination
171 * - async : Status will be returned immediately if supported.
172 * If the status is OK, then its value field will be
173 * set to a FileBackendStoreOpHandle object.
175 * @param $params Array
178 final public function copyInternal( array $params ) {
179 wfProfileIn( __METHOD__
);
180 wfProfileIn( __METHOD__
. '-' . $this->name
);
181 $status = $this->doCopyInternal( $params );
182 $this->clearCache( array( $params['dst'] ) );
183 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
184 $this->deleteFileCache( $params['dst'] ); // persistent cache
186 wfProfileOut( __METHOD__
. '-' . $this->name
);
187 wfProfileOut( __METHOD__
);
192 * @see FileBackendStore::copyInternal()
194 abstract protected function doCopyInternal( array $params );
197 * Delete a file at the storage path.
198 * Do not call this function from places outside FileBackend and FileOp.
201 * - src : source storage path
202 * - ignoreMissingSource : do nothing if the source file does not exist
203 * - async : Status will be returned immediately if supported.
204 * If the status is OK, then its value field will be
205 * set to a FileBackendStoreOpHandle object.
207 * @param $params Array
210 final public function deleteInternal( array $params ) {
211 wfProfileIn( __METHOD__
);
212 wfProfileIn( __METHOD__
. '-' . $this->name
);
213 $status = $this->doDeleteInternal( $params );
214 $this->clearCache( array( $params['src'] ) );
215 $this->deleteFileCache( $params['src'] ); // persistent cache
216 wfProfileOut( __METHOD__
. '-' . $this->name
);
217 wfProfileOut( __METHOD__
);
222 * @see FileBackendStore::deleteInternal()
224 abstract protected function doDeleteInternal( array $params );
227 * Move a file from one storage path to another in the backend.
228 * Do not call this function from places outside FileBackend and FileOp.
231 * - src : source storage path
232 * - dst : destination storage path
233 * - overwrite : overwrite any file that exists at the destination
234 * - disposition : Content-Disposition header value for the destination
235 * - async : Status will be returned immediately if supported.
236 * If the status is OK, then its value field will be
237 * set to a FileBackendStoreOpHandle object.
239 * @param $params Array
242 final public function moveInternal( array $params ) {
243 wfProfileIn( __METHOD__
);
244 wfProfileIn( __METHOD__
. '-' . $this->name
);
245 $status = $this->doMoveInternal( $params );
246 $this->clearCache( array( $params['src'], $params['dst'] ) );
247 $this->deleteFileCache( $params['src'] ); // persistent cache
248 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
249 $this->deleteFileCache( $params['dst'] ); // persistent cache
251 wfProfileOut( __METHOD__
. '-' . $this->name
);
252 wfProfileOut( __METHOD__
);
257 * @see FileBackendStore::moveInternal()
260 protected function doMoveInternal( array $params ) {
261 unset( $params['async'] ); // two steps, won't work here :)
262 // Copy source to dest
263 $status = $this->copyInternal( $params );
264 if ( $status->isOK() ) {
265 // Delete source (only fails due to races or medium going down)
266 $status->merge( $this->deleteInternal( array( 'src' => $params['src'] ) ) );
267 $status->setResult( true, $status->value
); // ignore delete() errors
273 * No-op file operation that does nothing.
274 * Do not call this function from places outside FileBackend and FileOp.
276 * @param $params Array
279 final public function nullInternal( array $params ) {
280 return Status
::newGood();
284 * @see FileBackend::concatenate()
287 final public function concatenate( array $params ) {
288 wfProfileIn( __METHOD__
);
289 wfProfileIn( __METHOD__
. '-' . $this->name
);
290 $status = Status
::newGood();
292 // Try to lock the source files for the scope of this function
293 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager
::LOCK_UW
, $status );
294 if ( $status->isOK() ) {
295 // Actually do the file concatenation...
296 $start_time = microtime( true );
297 $status->merge( $this->doConcatenate( $params ) );
298 $sec = microtime( true ) - $start_time;
299 if ( !$status->isOK() ) {
300 wfDebugLog( 'FileOperation', get_class( $this ) . " failed to concatenate " .
301 count( $params['srcs'] ) . " file(s) [$sec sec]" );
305 wfProfileOut( __METHOD__
. '-' . $this->name
);
306 wfProfileOut( __METHOD__
);
311 * @see FileBackendStore::concatenate()
314 protected function doConcatenate( array $params ) {
315 $status = Status
::newGood();
316 $tmpPath = $params['dst']; // convenience
318 // Check that the specified temp file is valid...
319 wfSuppressWarnings();
320 $ok = ( is_file( $tmpPath ) && !filesize( $tmpPath ) );
322 if ( !$ok ) { // not present or not empty
323 $status->fatal( 'backend-fail-opentemp', $tmpPath );
327 // Build up the temp file using the source chunks (in order)...
328 $tmpHandle = fopen( $tmpPath, 'ab' );
329 if ( $tmpHandle === false ) {
330 $status->fatal( 'backend-fail-opentemp', $tmpPath );
333 foreach ( $params['srcs'] as $virtualSource ) {
334 // Get a local FS version of the chunk
335 $tmpFile = $this->getLocalReference( array( 'src' => $virtualSource ) );
337 $status->fatal( 'backend-fail-read', $virtualSource );
340 // Get a handle to the local FS version
341 $sourceHandle = fopen( $tmpFile->getPath(), 'r' );
342 if ( $sourceHandle === false ) {
343 fclose( $tmpHandle );
344 $status->fatal( 'backend-fail-read', $virtualSource );
347 // Append chunk to file (pass chunk size to avoid magic quotes)
348 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
349 fclose( $sourceHandle );
350 fclose( $tmpHandle );
351 $status->fatal( 'backend-fail-writetemp', $tmpPath );
354 fclose( $sourceHandle );
356 if ( !fclose( $tmpHandle ) ) {
357 $status->fatal( 'backend-fail-closetemp', $tmpPath );
361 clearstatcache(); // temp file changed
367 * @see FileBackend::doPrepare()
370 final protected function doPrepare( array $params ) {
371 wfProfileIn( __METHOD__
);
372 wfProfileIn( __METHOD__
. '-' . $this->name
);
374 $status = Status
::newGood();
375 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
376 if ( $dir === null ) {
377 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
378 wfProfileOut( __METHOD__
. '-' . $this->name
);
379 wfProfileOut( __METHOD__
);
380 return $status; // invalid storage path
383 if ( $shard !== null ) { // confined to a single container/shard
384 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
385 } else { // directory is on several shards
386 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
387 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
388 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
389 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
393 wfProfileOut( __METHOD__
. '-' . $this->name
);
394 wfProfileOut( __METHOD__
);
399 * @see FileBackendStore::doPrepare()
402 protected function doPrepareInternal( $container, $dir, array $params ) {
403 return Status
::newGood();
407 * @see FileBackend::doSecure()
410 final protected function doSecure( array $params ) {
411 wfProfileIn( __METHOD__
);
412 wfProfileIn( __METHOD__
. '-' . $this->name
);
413 $status = Status
::newGood();
415 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
416 if ( $dir === null ) {
417 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
418 wfProfileOut( __METHOD__
. '-' . $this->name
);
419 wfProfileOut( __METHOD__
);
420 return $status; // invalid storage path
423 if ( $shard !== null ) { // confined to a single container/shard
424 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
425 } else { // directory is on several shards
426 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
427 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
428 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
429 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
433 wfProfileOut( __METHOD__
. '-' . $this->name
);
434 wfProfileOut( __METHOD__
);
439 * @see FileBackendStore::doSecure()
442 protected function doSecureInternal( $container, $dir, array $params ) {
443 return Status
::newGood();
447 * @see FileBackend::doPublish()
450 final protected function doPublish( array $params ) {
451 wfProfileIn( __METHOD__
);
452 wfProfileIn( __METHOD__
. '-' . $this->name
);
453 $status = Status
::newGood();
455 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
456 if ( $dir === null ) {
457 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
458 wfProfileOut( __METHOD__
. '-' . $this->name
);
459 wfProfileOut( __METHOD__
);
460 return $status; // invalid storage path
463 if ( $shard !== null ) { // confined to a single container/shard
464 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
465 } else { // directory is on several shards
466 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
467 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
468 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
469 $status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
473 wfProfileOut( __METHOD__
. '-' . $this->name
);
474 wfProfileOut( __METHOD__
);
479 * @see FileBackendStore::doPublish()
482 protected function doPublishInternal( $container, $dir, array $params ) {
483 return Status
::newGood();
487 * @see FileBackend::doClean()
490 final protected function doClean( array $params ) {
491 wfProfileIn( __METHOD__
);
492 wfProfileIn( __METHOD__
. '-' . $this->name
);
493 $status = Status
::newGood();
495 // Recursive: first delete all empty subdirs recursively
496 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
497 $subDirsRel = $this->getTopDirectoryList( array( 'dir' => $params['dir'] ) );
498 if ( $subDirsRel !== null ) { // no errors
499 foreach ( $subDirsRel as $subDirRel ) {
500 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
501 $status->merge( $this->doClean( array( 'dir' => $subDir ) +
$params ) );
506 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
507 if ( $dir === null ) {
508 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
509 wfProfileOut( __METHOD__
. '-' . $this->name
);
510 wfProfileOut( __METHOD__
);
511 return $status; // invalid storage path
514 // Attempt to lock this directory...
515 $filesLockEx = array( $params['dir'] );
516 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
517 if ( !$status->isOK() ) {
518 wfProfileOut( __METHOD__
. '-' . $this->name
);
519 wfProfileOut( __METHOD__
);
520 return $status; // abort
523 if ( $shard !== null ) { // confined to a single container/shard
524 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
525 $this->deleteContainerCache( $fullCont ); // purge cache
526 } else { // directory is on several shards
527 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
528 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
529 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
530 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
531 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
535 wfProfileOut( __METHOD__
. '-' . $this->name
);
536 wfProfileOut( __METHOD__
);
541 * @see FileBackendStore::doClean()
544 protected function doCleanInternal( $container, $dir, array $params ) {
545 return Status
::newGood();
549 * @see FileBackend::fileExists()
552 final public function fileExists( array $params ) {
553 wfProfileIn( __METHOD__
);
554 wfProfileIn( __METHOD__
. '-' . $this->name
);
555 $stat = $this->getFileStat( $params );
556 wfProfileOut( __METHOD__
. '-' . $this->name
);
557 wfProfileOut( __METHOD__
);
558 return ( $stat === null ) ?
null : (bool)$stat; // null => failure
562 * @see FileBackend::getFileTimestamp()
565 final public function getFileTimestamp( array $params ) {
566 wfProfileIn( __METHOD__
);
567 wfProfileIn( __METHOD__
. '-' . $this->name
);
568 $stat = $this->getFileStat( $params );
569 wfProfileOut( __METHOD__
. '-' . $this->name
);
570 wfProfileOut( __METHOD__
);
571 return $stat ?
$stat['mtime'] : false;
575 * @see FileBackend::getFileSize()
578 final public function getFileSize( array $params ) {
579 wfProfileIn( __METHOD__
);
580 wfProfileIn( __METHOD__
. '-' . $this->name
);
581 $stat = $this->getFileStat( $params );
582 wfProfileOut( __METHOD__
. '-' . $this->name
);
583 wfProfileOut( __METHOD__
);
584 return $stat ?
$stat['size'] : false;
588 * @see FileBackend::getFileStat()
591 final public function getFileStat( array $params ) {
592 $path = self
::normalizeStoragePath( $params['src'] );
593 if ( $path === null ) {
594 return false; // invalid storage path
596 wfProfileIn( __METHOD__
);
597 wfProfileIn( __METHOD__
. '-' . $this->name
);
598 $latest = !empty( $params['latest'] ); // use latest data?
599 if ( !$this->cheapCache
->has( $path, 'stat' ) ) {
600 $this->primeFileCache( array( $path ) ); // check persistent cache
602 if ( $this->cheapCache
->has( $path, 'stat' ) ) {
603 $stat = $this->cheapCache
->get( $path, 'stat' );
604 // If we want the latest data, check that this cached
605 // value was in fact fetched with the latest available data.
606 if ( !$latest ||
$stat['latest'] ) {
607 wfProfileOut( __METHOD__
. '-' . $this->name
);
608 wfProfileOut( __METHOD__
);
612 wfProfileIn( __METHOD__
. '-miss' );
613 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
614 $stat = $this->doGetFileStat( $params );
615 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
616 wfProfileOut( __METHOD__
. '-miss' );
617 if ( is_array( $stat ) ) { // don't cache negatives
618 $stat['latest'] = $latest;
619 $this->cheapCache
->set( $path, 'stat', $stat );
620 $this->setFileCache( $path, $stat ); // update persistent cache
621 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
622 $this->cheapCache
->set( $path, 'sha1',
623 array( 'hash' => $stat['sha1'], 'latest' => $latest ) );
626 wfDebug( __METHOD__
. ": File $path does not exist.\n" );
628 wfProfileOut( __METHOD__
. '-' . $this->name
);
629 wfProfileOut( __METHOD__
);
634 * @see FileBackendStore::getFileStat()
636 abstract protected function doGetFileStat( array $params );
639 * @see FileBackend::getFileContents()
640 * @return bool|string
642 public function getFileContents( array $params ) {
643 wfProfileIn( __METHOD__
);
644 wfProfileIn( __METHOD__
. '-' . $this->name
);
645 $tmpFile = $this->getLocalReference( $params );
647 wfProfileOut( __METHOD__
. '-' . $this->name
);
648 wfProfileOut( __METHOD__
);
651 wfSuppressWarnings();
652 $data = file_get_contents( $tmpFile->getPath() );
654 wfProfileOut( __METHOD__
. '-' . $this->name
);
655 wfProfileOut( __METHOD__
);
660 * @see FileBackend::getFileSha1Base36()
661 * @return bool|string
663 final public function getFileSha1Base36( array $params ) {
664 $path = self
::normalizeStoragePath( $params['src'] );
665 if ( $path === null ) {
666 return false; // invalid storage path
668 wfProfileIn( __METHOD__
);
669 wfProfileIn( __METHOD__
. '-' . $this->name
);
670 $latest = !empty( $params['latest'] ); // use latest data?
671 if ( $this->cheapCache
->has( $path, 'sha1' ) ) {
672 $stat = $this->cheapCache
->get( $path, 'sha1' );
673 // If we want the latest data, check that this cached
674 // value was in fact fetched with the latest available data.
675 if ( !$latest ||
$stat['latest'] ) {
676 wfProfileOut( __METHOD__
. '-' . $this->name
);
677 wfProfileOut( __METHOD__
);
678 return $stat['hash'];
681 wfProfileIn( __METHOD__
. '-miss' );
682 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
683 $hash = $this->doGetFileSha1Base36( $params );
684 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
685 wfProfileOut( __METHOD__
. '-miss' );
686 if ( $hash ) { // don't cache negatives
687 $this->cheapCache
->set( $path, 'sha1',
688 array( 'hash' => $hash, 'latest' => $latest ) );
690 wfProfileOut( __METHOD__
. '-' . $this->name
);
691 wfProfileOut( __METHOD__
);
696 * @see FileBackendStore::getFileSha1Base36()
697 * @return bool|string
699 protected function doGetFileSha1Base36( array $params ) {
700 $fsFile = $this->getLocalReference( $params );
704 return $fsFile->getSha1Base36();
709 * @see FileBackend::getFileProps()
712 final public function getFileProps( array $params ) {
713 wfProfileIn( __METHOD__
);
714 wfProfileIn( __METHOD__
. '-' . $this->name
);
715 $fsFile = $this->getLocalReference( $params );
716 $props = $fsFile ?
$fsFile->getProps() : FSFile
::placeholderProps();
717 wfProfileOut( __METHOD__
. '-' . $this->name
);
718 wfProfileOut( __METHOD__
);
723 * @see FileBackend::getLocalReference()
724 * @return TempFSFile|null
726 public function getLocalReference( array $params ) {
727 $path = self
::normalizeStoragePath( $params['src'] );
728 if ( $path === null ) {
729 return null; // invalid storage path
731 wfProfileIn( __METHOD__
);
732 wfProfileIn( __METHOD__
. '-' . $this->name
);
733 $latest = !empty( $params['latest'] ); // use latest data?
734 if ( $this->expensiveCache
->has( $path, 'localRef' ) ) {
735 $val = $this->expensiveCache
->get( $path, 'localRef' );
736 // If we want the latest data, check that this cached
737 // value was in fact fetched with the latest available data.
738 if ( !$latest ||
$val['latest'] ) {
739 wfProfileOut( __METHOD__
. '-' . $this->name
);
740 wfProfileOut( __METHOD__
);
741 return $val['object'];
744 $tmpFile = $this->getLocalCopy( $params );
745 if ( $tmpFile ) { // don't cache negatives
746 $this->expensiveCache
->set( $path, 'localRef',
747 array( 'object' => $tmpFile, 'latest' => $latest ) );
749 wfProfileOut( __METHOD__
. '-' . $this->name
);
750 wfProfileOut( __METHOD__
);
755 * @see FileBackend::streamFile()
758 final public function streamFile( array $params ) {
759 wfProfileIn( __METHOD__
);
760 wfProfileIn( __METHOD__
. '-' . $this->name
);
761 $status = Status
::newGood();
763 $info = $this->getFileStat( $params );
764 if ( !$info ) { // let StreamFile handle the 404
765 $status->fatal( 'backend-fail-notexists', $params['src'] );
768 // Set output buffer and HTTP headers for stream
769 $extraHeaders = isset( $params['headers'] ) ?
$params['headers'] : array();
770 $res = StreamFile
::prepareForStream( $params['src'], $info, $extraHeaders );
771 if ( $res == StreamFile
::NOT_MODIFIED
) {
772 // do nothing; client cache is up to date
773 } elseif ( $res == StreamFile
::READY_STREAM
) {
774 wfProfileIn( __METHOD__
. '-send' );
775 wfProfileIn( __METHOD__
. '-send-' . $this->name
);
776 $status = $this->doStreamFile( $params );
777 wfProfileOut( __METHOD__
. '-send-' . $this->name
);
778 wfProfileOut( __METHOD__
. '-send' );
780 $status->fatal( 'backend-fail-stream', $params['src'] );
783 wfProfileOut( __METHOD__
. '-' . $this->name
);
784 wfProfileOut( __METHOD__
);
789 * @see FileBackendStore::streamFile()
792 protected function doStreamFile( array $params ) {
793 $status = Status
::newGood();
795 $fsFile = $this->getLocalReference( $params );
797 $status->fatal( 'backend-fail-stream', $params['src'] );
798 } elseif ( !readfile( $fsFile->getPath() ) ) {
799 $status->fatal( 'backend-fail-stream', $params['src'] );
806 * @see FileBackend::directoryExists()
809 final public function directoryExists( array $params ) {
810 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
811 if ( $dir === null ) {
812 return false; // invalid storage path
814 if ( $shard !== null ) { // confined to a single container/shard
815 return $this->doDirectoryExists( $fullCont, $dir, $params );
816 } else { // directory is on several shards
817 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
818 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
819 $res = false; // response
820 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
821 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
825 } elseif ( $exists === null ) { // error?
826 $res = null; // if we don't find anything, it is indeterminate
834 * @see FileBackendStore::directoryExists()
836 * @param $container string Resolved container name
837 * @param $dir string Resolved path relative to container
838 * @param $params Array
841 abstract protected function doDirectoryExists( $container, $dir, array $params );
844 * @see FileBackend::getDirectoryList()
845 * @return Traversable|Array|null Returns null on failure
847 final public function getDirectoryList( array $params ) {
848 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
849 if ( $dir === null ) { // invalid storage path
852 if ( $shard !== null ) {
853 // File listing is confined to a single container/shard
854 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
856 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
857 // File listing spans multiple containers/shards
858 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
859 return new FileBackendStoreShardDirIterator( $this,
860 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
865 * Do not call this function from places outside FileBackend
867 * @see FileBackendStore::getDirectoryList()
869 * @param $container string Resolved container name
870 * @param $dir string Resolved path relative to container
871 * @param $params Array
872 * @return Traversable|Array|null Returns null on failure
874 abstract public function getDirectoryListInternal( $container, $dir, array $params );
877 * @see FileBackend::getFileList()
878 * @return Traversable|Array|null Returns null on failure
880 final public function getFileList( array $params ) {
881 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
882 if ( $dir === null ) { // invalid storage path
885 if ( $shard !== null ) {
886 // File listing is confined to a single container/shard
887 return $this->getFileListInternal( $fullCont, $dir, $params );
889 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
890 // File listing spans multiple containers/shards
891 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
892 return new FileBackendStoreShardFileIterator( $this,
893 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
898 * Do not call this function from places outside FileBackend
900 * @see FileBackendStore::getFileList()
902 * @param $container string Resolved container name
903 * @param $dir string Resolved path relative to container
904 * @param $params Array
905 * @return Traversable|Array|null Returns null on failure
907 abstract public function getFileListInternal( $container, $dir, array $params );
910 * Return a list of FileOp objects from a list of operations.
911 * Do not call this function from places outside FileBackend.
913 * The result must have the same number of items as the input.
914 * An exception is thrown if an unsupported operation is requested.
916 * @param $ops Array Same format as doOperations()
917 * @return Array List of FileOp objects
918 * @throws MWException
920 final public function getOperationsInternal( array $ops ) {
921 $supportedOps = array(
922 'store' => 'StoreFileOp',
923 'copy' => 'CopyFileOp',
924 'move' => 'MoveFileOp',
925 'delete' => 'DeleteFileOp',
926 'create' => 'CreateFileOp',
927 'null' => 'NullFileOp'
930 $performOps = array(); // array of FileOp objects
931 // Build up ordered array of FileOps...
932 foreach ( $ops as $operation ) {
933 $opName = $operation['op'];
934 if ( isset( $supportedOps[$opName] ) ) {
935 $class = $supportedOps[$opName];
936 // Get params for this operation
937 $params = $operation;
938 // Append the FileOp class
939 $performOps[] = new $class( $this, $params );
941 throw new MWException( "Operation '$opName' is not supported." );
949 * Get a list of storage paths to lock for a list of operations
950 * Returns an array with 'sh' (shared) and 'ex' (exclusive) keys,
951 * each corresponding to a list of storage paths to be locked.
953 * @param $performOps Array List of FileOp objects
954 * @return Array ('sh' => list of paths, 'ex' => list of paths)
956 final public function getPathsToLockForOpsInternal( array $performOps ) {
957 // Build up a list of files to lock...
958 $paths = array( 'sh' => array(), 'ex' => array() );
959 foreach ( $performOps as $fileOp ) {
960 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
961 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
963 // Optimization: if doing an EX lock anyway, don't also set an SH one
964 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
965 // Get a shared lock on the parent directory of each path changed
966 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
972 * @see FileBackend::getScopedLocksForOps()
975 public function getScopedLocksForOps( array $ops, Status
$status ) {
976 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
978 $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status ),
979 $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status )
984 * @see FileBackend::doOperationsInternal()
987 final protected function doOperationsInternal( array $ops, array $opts ) {
988 wfProfileIn( __METHOD__
);
989 wfProfileIn( __METHOD__
. '-' . $this->name
);
990 $status = Status
::newGood();
992 // Build up a list of FileOps...
993 $performOps = $this->getOperationsInternal( $ops );
995 // Acquire any locks as needed...
996 if ( empty( $opts['nonLocking'] ) ) {
997 // Build up a list of files to lock...
998 $paths = $this->getPathsToLockForOpsInternal( $performOps );
999 // Try to lock those files for the scope of this function...
1000 $scopeLockS = $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status );
1001 $scopeLockE = $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status );
1002 if ( !$status->isOK() ) {
1003 wfProfileOut( __METHOD__
. '-' . $this->name
);
1004 wfProfileOut( __METHOD__
);
1005 return $status; // abort
1009 // Clear any file cache entries (after locks acquired)
1010 if ( empty( $opts['preserveCache'] ) ) {
1011 $this->clearCache();
1014 // Load from the persistent file and container caches
1015 $this->primeFileCache( $performOps );
1016 $this->primeContainerCache( $performOps );
1018 // Actually attempt the operation batch...
1019 $subStatus = FileOpBatch
::attempt( $performOps, $opts, $this->fileJournal
);
1021 // Merge errors into status fields
1022 $status->merge( $subStatus );
1023 $status->success
= $subStatus->success
; // not done in merge()
1025 wfProfileOut( __METHOD__
. '-' . $this->name
);
1026 wfProfileOut( __METHOD__
);
1031 * @see FileBackend::doQuickOperationsInternal()
1033 * @throws MWException
1035 final protected function doQuickOperationsInternal( array $ops ) {
1036 wfProfileIn( __METHOD__
);
1037 wfProfileIn( __METHOD__
. '-' . $this->name
);
1038 $status = Status
::newGood();
1040 $supportedOps = array( 'create', 'store', 'copy', 'move', 'delete', 'null' );
1041 $async = ( $this->parallelize
=== 'implicit' );
1042 $maxConcurrency = $this->concurrency
; // throttle
1044 $statuses = array(); // array of (index => Status)
1045 $fileOpHandles = array(); // list of (index => handle) arrays
1046 $curFileOpHandles = array(); // current handle batch
1047 // Perform the sync-only ops and build up op handles for the async ops...
1048 foreach ( $ops as $index => $params ) {
1049 if ( !in_array( $params['op'], $supportedOps ) ) {
1050 wfProfileOut( __METHOD__
. '-' . $this->name
);
1051 wfProfileOut( __METHOD__
);
1052 throw new MWException( "Operation '{$params['op']}' is not supported." );
1054 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1055 $subStatus = $this->$method( array( 'async' => $async ) +
$params );
1056 if ( $subStatus->value
instanceof FileBackendStoreOpHandle
) { // async
1057 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1058 $fileOpHandles[] = $curFileOpHandles; // push this batch
1059 $curFileOpHandles = array();
1061 $curFileOpHandles[$index] = $subStatus->value
; // keep index
1062 } else { // error or completed
1063 $statuses[$index] = $subStatus; // keep index
1066 if ( count( $curFileOpHandles ) ) {
1067 $fileOpHandles[] = $curFileOpHandles; // last batch
1069 // Do all the async ops that can be done concurrently...
1070 foreach ( $fileOpHandles as $fileHandleBatch ) {
1071 $statuses = $statuses +
$this->executeOpHandlesInternal( $fileHandleBatch );
1073 // Marshall and merge all the responses...
1074 foreach ( $statuses as $index => $subStatus ) {
1075 $status->merge( $subStatus );
1076 if ( $subStatus->isOK() ) {
1077 $status->success
[$index] = true;
1078 ++
$status->successCount
;
1080 $status->success
[$index] = false;
1081 ++
$status->failCount
;
1085 wfProfileOut( __METHOD__
. '-' . $this->name
);
1086 wfProfileOut( __METHOD__
);
1091 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1092 * The resulting Status object fields will correspond
1093 * to the order in which the handles where given.
1095 * @param $handles Array List of FileBackendStoreOpHandle objects
1096 * @return Array Map of Status objects
1097 * @throws MWException
1099 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1100 wfProfileIn( __METHOD__
);
1101 wfProfileIn( __METHOD__
. '-' . $this->name
);
1102 foreach ( $fileOpHandles as $fileOpHandle ) {
1103 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle
) ) {
1104 throw new MWException( "Given a non-FileBackendStoreOpHandle object." );
1105 } elseif ( $fileOpHandle->backend
->getName() !== $this->getName() ) {
1106 throw new MWException( "Given a FileBackendStoreOpHandle for the wrong backend." );
1109 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1110 foreach ( $fileOpHandles as $fileOpHandle ) {
1111 $fileOpHandle->closeResources();
1113 wfProfileOut( __METHOD__
. '-' . $this->name
);
1114 wfProfileOut( __METHOD__
);
1119 * @see FileBackendStore::executeOpHandlesInternal()
1120 * @return Array List of corresponding Status objects
1122 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1123 foreach ( $fileOpHandles as $fileOpHandle ) { // OK if empty
1124 throw new MWException( "This backend supports no asynchronous operations." );
1130 * @see FileBackend::preloadCache()
1132 final public function preloadCache( array $paths ) {
1133 $fullConts = array(); // full container names
1134 foreach ( $paths as $path ) {
1135 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1136 $fullConts[] = $fullCont;
1138 // Load from the persistent file and container caches
1139 $this->primeContainerCache( $fullConts );
1140 $this->primeFileCache( $paths );
1144 * @see FileBackend::clearCache()
1146 final public function clearCache( array $paths = null ) {
1147 if ( is_array( $paths ) ) {
1148 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1149 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1151 if ( $paths === null ) {
1152 $this->cheapCache
->clear();
1153 $this->expensiveCache
->clear();
1155 foreach ( $paths as $path ) {
1156 $this->cheapCache
->clear( $path );
1157 $this->expensiveCache
->clear( $path );
1160 $this->doClearCache( $paths );
1164 * Clears any additional stat caches for storage paths
1166 * @see FileBackend::clearCache()
1168 * @param $paths Array Storage paths (optional)
1171 protected function doClearCache( array $paths = null ) {}
1174 * Is this a key/value store where directories are just virtual?
1175 * Virtual directories exists in so much as files exists that are
1176 * prefixed with the directory path followed by a forward slash.
1180 abstract protected function directoriesAreVirtual();
1183 * Check if a container name is valid.
1184 * This checks for for length and illegal characters.
1186 * @param $container string
1189 final protected static function isValidContainerName( $container ) {
1190 // This accounts for Swift and S3 restrictions while leaving room
1191 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1192 // This disallows directory separators or traversal characters.
1193 // Note that matching strings URL encode to the same string;
1194 // in Swift, the length restriction is *after* URL encoding.
1195 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1199 * Splits a storage path into an internal container name,
1200 * an internal relative file name, and a container shard suffix.
1201 * Any shard suffix is already appended to the internal container name.
1202 * This also checks that the storage path is valid and within this backend.
1204 * If the container is sharded but a suffix could not be determined,
1205 * this means that the path can only refer to a directory and can only
1206 * be scanned by looking in all the container shards.
1208 * @param $storagePath string
1209 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1211 final protected function resolveStoragePath( $storagePath ) {
1212 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1213 if ( $backend === $this->name
) { // must be for this backend
1214 $relPath = self
::normalizeContainerPath( $relPath );
1215 if ( $relPath !== null ) {
1216 // Get shard for the normalized path if this container is sharded
1217 $cShard = $this->getContainerShard( $container, $relPath );
1218 // Validate and sanitize the relative path (backend-specific)
1219 $relPath = $this->resolveContainerPath( $container, $relPath );
1220 if ( $relPath !== null ) {
1221 // Prepend any wiki ID prefix to the container name
1222 $container = $this->fullContainerName( $container );
1223 if ( self
::isValidContainerName( $container ) ) {
1224 // Validate and sanitize the container name (backend-specific)
1225 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1226 if ( $container !== null ) {
1227 return array( $container, $relPath, $cShard );
1233 return array( null, null, null );
1237 * Like resolveStoragePath() except null values are returned if
1238 * the container is sharded and the shard could not be determined.
1240 * @see FileBackendStore::resolveStoragePath()
1242 * @param $storagePath string
1243 * @return Array (container, path) or (null, null) if invalid
1245 final protected function resolveStoragePathReal( $storagePath ) {
1246 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1247 if ( $cShard !== null ) {
1248 return array( $container, $relPath );
1250 return array( null, null );
1254 * Get the container name shard suffix for a given path.
1255 * Any empty suffix means the container is not sharded.
1257 * @param $container string Container name
1258 * @param $relPath string Storage path relative to the container
1259 * @return string|null Returns null if shard could not be determined
1261 final protected function getContainerShard( $container, $relPath ) {
1262 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1263 if ( $levels == 1 ||
$levels == 2 ) {
1264 // Hash characters are either base 16 or 36
1265 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1266 // Get a regex that represents the shard portion of paths.
1267 // The concatenation of the captures gives us the shard.
1268 if ( $levels === 1 ) { // 16 or 36 shards per container
1269 $hashDirRegex = '(' . $char . ')';
1270 } else { // 256 or 1296 shards per container
1271 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1272 $hashDirRegex = $char . '/(' . $char . '{2})';
1273 } else { // short hash dir format (e.g. "a/b/c")
1274 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1277 // Allow certain directories to be above the hash dirs so as
1278 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1279 // They must be 2+ chars to avoid any hash directory ambiguity.
1281 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1282 return '.' . implode( '', array_slice( $m, 1 ) );
1284 return null; // failed to match
1286 return ''; // no sharding
1290 * Check if a storage path maps to a single shard.
1291 * Container dirs like "a", where the container shards on "x/xy",
1292 * can reside on several shards. Such paths are tricky to handle.
1294 * @param $storagePath string Storage path
1297 final public function isSingleShardPathInternal( $storagePath ) {
1298 list( $c, $r, $shard ) = $this->resolveStoragePath( $storagePath );
1299 return ( $shard !== null );
1303 * Get the sharding config for a container.
1304 * If greater than 0, then all file storage paths within
1305 * the container are required to be hashed accordingly.
1307 * @param $container string
1308 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
1310 final protected function getContainerHashLevels( $container ) {
1311 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1312 $config = $this->shardViaHashLevels
[$container];
1313 $hashLevels = (int)$config['levels'];
1314 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1315 $hashBase = (int)$config['base'];
1316 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1317 return array( $hashLevels, $hashBase, $config['repeat'] );
1321 return array( 0, 0, false ); // no sharding
1325 * Get a list of full container shard suffixes for a container
1327 * @param $container string
1330 final protected function getContainerSuffixes( $container ) {
1332 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1333 if ( $digits > 0 ) {
1334 $numShards = pow( $base, $digits );
1335 for ( $index = 0; $index < $numShards; $index++
) {
1336 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1343 * Get the full container name, including the wiki ID prefix
1345 * @param $container string
1348 final protected function fullContainerName( $container ) {
1349 if ( $this->wikiId
!= '' ) {
1350 return "{$this->wikiId}-$container";
1357 * Resolve a container name, checking if it's allowed by the backend.
1358 * This is intended for internal use, such as encoding illegal chars.
1359 * Subclasses can override this to be more restrictive.
1361 * @param $container string
1362 * @return string|null
1364 protected function resolveContainerName( $container ) {
1369 * Resolve a relative storage path, checking if it's allowed by the backend.
1370 * This is intended for internal use, such as encoding illegal chars or perhaps
1371 * getting absolute paths (e.g. FS based backends). Note that the relative path
1372 * may be the empty string (e.g. the path is simply to the container).
1374 * @param $container string Container name
1375 * @param $relStoragePath string Storage path relative to the container
1376 * @return string|null Path or null if not valid
1378 protected function resolveContainerPath( $container, $relStoragePath ) {
1379 return $relStoragePath;
1383 * Get the cache key for a container
1385 * @param $container string Resolved container name
1388 private function containerCacheKey( $container ) {
1389 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1393 * Set the cached info for a container
1395 * @param $container string Resolved container name
1396 * @param $val mixed Information to cache
1398 final protected function setContainerCache( $container, $val ) {
1399 $this->memCache
->add( $this->containerCacheKey( $container ), $val, 14*86400 );
1403 * Delete the cached info for a container.
1404 * The cache key is salted for a while to prevent race conditions.
1406 * @param $container string Resolved container name
1408 final protected function deleteContainerCache( $container ) {
1409 if ( !$this->memCache
->set( $this->containerCacheKey( $container ), 'PURGED', 300 ) ) {
1410 trigger_error( "Unable to delete stat cache for container $container." );
1415 * Do a batch lookup from cache for container stats for all containers
1416 * used in a list of container names, storage paths, or FileOp objects.
1418 * @param $items Array
1421 final protected function primeContainerCache( array $items ) {
1422 wfProfileIn( __METHOD__
);
1423 wfProfileIn( __METHOD__
. '-' . $this->name
);
1425 $paths = array(); // list of storage paths
1426 $contNames = array(); // (cache key => resolved container name)
1427 // Get all the paths/containers from the items...
1428 foreach ( $items as $item ) {
1429 if ( $item instanceof FileOp
) {
1430 $paths = array_merge( $paths, $item->storagePathsRead() );
1431 $paths = array_merge( $paths, $item->storagePathsChanged() );
1432 } elseif ( self
::isStoragePath( $item ) ) {
1434 } elseif ( is_string( $item ) ) { // full container name
1435 $contNames[$this->containerCacheKey( $item )] = $item;
1438 // Get all the corresponding cache keys for paths...
1439 foreach ( $paths as $path ) {
1440 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1441 if ( $fullCont !== null ) { // valid path for this backend
1442 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1446 $contInfo = array(); // (resolved container name => cache value)
1447 // Get all cache entries for these container cache keys...
1448 $values = $this->memCache
->getMulti( array_keys( $contNames ) );
1449 foreach ( $values as $cacheKey => $val ) {
1450 $contInfo[$contNames[$cacheKey]] = $val;
1453 // Populate the container process cache for the backend...
1454 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1456 wfProfileOut( __METHOD__
. '-' . $this->name
);
1457 wfProfileOut( __METHOD__
);
1461 * Fill the backend-specific process cache given an array of
1462 * resolved container names and their corresponding cached info.
1463 * Only containers that actually exist should appear in the map.
1465 * @param $containerInfo Array Map of resolved container names to cached info
1468 protected function doPrimeContainerCache( array $containerInfo ) {}
1471 * Get the cache key for a file path
1473 * @param $path string Storage path
1476 private function fileCacheKey( $path ) {
1477 return wfMemcKey( 'backend', $this->getName(), 'file', sha1( $path ) );
1481 * Set the cached stat info for a file path.
1482 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1483 * salting for the case when a file is created at a path were there was none before.
1485 * @param $path string Storage path
1486 * @param $val mixed Information to cache
1488 final protected function setFileCache( $path, $val ) {
1489 $this->memCache
->add( $this->fileCacheKey( $path ), $val, 7*86400 );
1493 * Delete the cached stat info for a file path.
1494 * The cache key is salted for a while to prevent race conditions.
1496 * @param $path string Storage path
1498 final protected function deleteFileCache( $path ) {
1499 if ( !$this->memCache
->set( $this->fileCacheKey( $path ), 'PURGED', 300 ) ) {
1500 trigger_error( "Unable to delete stat cache for file $path." );
1505 * Do a batch lookup from cache for file stats for all paths
1506 * used in a list of storage paths or FileOp objects.
1508 * @param $items Array List of storage paths or FileOps
1511 final protected function primeFileCache( array $items ) {
1512 wfProfileIn( __METHOD__
);
1513 wfProfileIn( __METHOD__
. '-' . $this->name
);
1515 $paths = array(); // list of storage paths
1516 $pathNames = array(); // (cache key => storage path)
1517 // Get all the paths/containers from the items...
1518 foreach ( $items as $item ) {
1519 if ( $item instanceof FileOp
) {
1520 $paths = array_merge( $paths, $item->storagePathsRead() );
1521 $paths = array_merge( $paths, $item->storagePathsChanged() );
1522 } elseif ( self
::isStoragePath( $item ) ) {
1526 // Get all the corresponding cache keys for paths...
1527 foreach ( $paths as $path ) {
1528 list( $cont, $rel, $s ) = $this->resolveStoragePath( $path );
1529 if ( $rel !== null ) { // valid path for this backend
1530 $pathNames[$this->fileCacheKey( $path )] = $path;
1533 // Get all cache entries for these container cache keys...
1534 $values = $this->memCache
->getMulti( array_keys( $pathNames ) );
1535 foreach ( $values as $cacheKey => $val ) {
1536 if ( is_array( $val ) ) {
1537 $path = $pathNames[$cacheKey];
1538 $this->cheapCache
->set( $path, 'stat', $val );
1539 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1540 $this->cheapCache
->set( $path, 'sha1',
1541 array( 'hash' => $val['sha1'], 'latest' => $val['latest'] ) );
1546 wfProfileOut( __METHOD__
. '-' . $this->name
);
1547 wfProfileOut( __METHOD__
);
1552 * FileBackendStore helper class for performing asynchronous file operations.
1554 * For example, calling FileBackendStore::createInternal() with the "async"
1555 * param flag may result in a Status that contains this object as a value.
1556 * This class is largely backend-specific and is mostly just "magic" to be
1557 * passed to FileBackendStore::executeOpHandlesInternal().
1559 abstract class FileBackendStoreOpHandle
{
1561 public $params = array(); // params to caller functions
1562 /** @var FileBackendStore */
1565 public $resourcesToClose = array();
1567 public $call; // string; name that identifies the function called
1570 * Close all open file handles
1574 public function closeResources() {
1575 array_map( 'fclose', $this->resourcesToClose
);
1580 * FileBackendStore helper function to handle listings that span container shards.
1581 * Do not use this class from places outside of FileBackendStore.
1583 * @ingroup FileBackend
1585 abstract class FileBackendStoreShardListIterator
implements Iterator
{
1586 /** @var FileBackendStore */
1591 protected $shardSuffixes;
1592 protected $container; // string; full container name
1593 protected $directory; // string; resolved relative path
1595 /** @var Traversable */
1597 protected $curShard = 0; // integer
1598 protected $pos = 0; // integer
1601 protected $multiShardPaths = array(); // (rel path => 1)
1604 * @param $backend FileBackendStore
1605 * @param $container string Full storage container name
1606 * @param $dir string Storage directory relative to container
1607 * @param $suffixes Array List of container shard suffixes
1608 * @param $params Array
1610 public function __construct(
1611 FileBackendStore
$backend, $container, $dir, array $suffixes, array $params
1613 $this->backend
= $backend;
1614 $this->container
= $container;
1615 $this->directory
= $dir;
1616 $this->shardSuffixes
= $suffixes;
1617 $this->params
= $params;
1621 * @see Iterator::key()
1624 public function key() {
1629 * @see Iterator::valid()
1632 public function valid() {
1633 if ( $this->iter
instanceof Iterator
) {
1634 return $this->iter
->valid();
1635 } elseif ( is_array( $this->iter
) ) {
1636 return ( current( $this->iter
) !== false ); // no paths can have this value
1638 return false; // some failure?
1642 * @see Iterator::current()
1643 * @return string|bool String or false
1645 public function current() {
1646 return ( $this->iter
instanceof Iterator
)
1647 ?
$this->iter
->current()
1648 : current( $this->iter
);
1652 * @see Iterator::next()
1655 public function next() {
1657 ( $this->iter
instanceof Iterator
) ?
$this->iter
->next() : next( $this->iter
);
1659 $continue = false; // keep scanning shards?
1660 $this->filterViaNext(); // filter out duplicates
1661 // Find the next non-empty shard if no elements are left
1662 if ( !$this->valid() ) {
1663 $this->nextShardIteratorIfNotValid();
1664 $continue = $this->valid(); // re-filter unless we ran out of shards
1666 } while ( $continue );
1670 * @see Iterator::rewind()
1673 public function rewind() {
1675 $this->curShard
= 0;
1676 $this->setIteratorFromCurrentShard();
1678 $continue = false; // keep scanning shards?
1679 $this->filterViaNext(); // filter out duplicates
1680 // Find the next non-empty shard if no elements are left
1681 if ( !$this->valid() ) {
1682 $this->nextShardIteratorIfNotValid();
1683 $continue = $this->valid(); // re-filter unless we ran out of shards
1685 } while ( $continue );
1689 * Filter out duplicate items by advancing to the next ones
1691 protected function filterViaNext() {
1692 while ( $this->valid() ) {
1693 $rel = $this->iter
->current(); // path relative to given directory
1694 $path = $this->params
['dir'] . "/{$rel}"; // full storage path
1695 if ( $this->backend
->isSingleShardPathInternal( $path ) ) {
1696 break; // path is only on one shard; no issue with duplicates
1697 } elseif ( isset( $this->multiShardPaths
[$rel] ) ) {
1698 // Don't keep listing paths that are on multiple shards
1699 ( $this->iter
instanceof Iterator
) ?
$this->iter
->next() : next( $this->iter
);
1701 $this->multiShardPaths
[$rel] = 1;
1708 * If the list iterator for this container shard is out of items,
1709 * then move on to the next container that has items.
1710 * If there are none, then it advances to the last container.
1712 protected function nextShardIteratorIfNotValid() {
1713 while ( !$this->valid() && ++
$this->curShard
< count( $this->shardSuffixes
) ) {
1714 $this->setIteratorFromCurrentShard();
1719 * Set the list iterator to that of the current container shard
1721 protected function setIteratorFromCurrentShard() {
1722 $this->iter
= $this->listFromShard(
1723 $this->container
. $this->shardSuffixes
[$this->curShard
],
1724 $this->directory
, $this->params
);
1725 // Start loading results so that current() works
1726 if ( $this->iter
) {
1727 ( $this->iter
instanceof Iterator
) ?
$this->iter
->rewind() : reset( $this->iter
);
1732 * Get the list for a given container shard
1734 * @param $container string Resolved container name
1735 * @param $dir string Resolved path relative to container
1736 * @param $params Array
1737 * @return Traversable|Array|null
1739 abstract protected function listFromShard( $container, $dir, array $params );
1743 * Iterator for listing directories
1745 class FileBackendStoreShardDirIterator
extends FileBackendStoreShardListIterator
{
1747 * @see FileBackendStoreShardListIterator::listFromShard()
1748 * @return Array|null|Traversable
1750 protected function listFromShard( $container, $dir, array $params ) {
1751 return $this->backend
->getDirectoryListInternal( $container, $dir, $params );
1756 * Iterator for listing regular files
1758 class FileBackendStoreShardFileIterator
extends FileBackendStoreShardListIterator
{
1760 * @see FileBackendStoreShardListIterator::listFromShard()
1761 * @return Array|null|Traversable
1763 protected function listFromShard( $container, $dir, array $params ) {
1764 return $this->backend
->getFileListInternal( $container, $dir, $params );