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 $opts = $this->setConcurrencyFlags( $opts );
1020 $subStatus = FileOpBatch
::attempt( $performOps, $opts, $this->fileJournal
);
1022 // Merge errors into status fields
1023 $status->merge( $subStatus );
1024 $status->success
= $subStatus->success
; // not done in merge()
1026 wfProfileOut( __METHOD__
. '-' . $this->name
);
1027 wfProfileOut( __METHOD__
);
1032 * @see FileBackend::doQuickOperationsInternal()
1034 * @throws MWException
1036 final protected function doQuickOperationsInternal( array $ops ) {
1037 wfProfileIn( __METHOD__
);
1038 wfProfileIn( __METHOD__
. '-' . $this->name
);
1039 $status = Status
::newGood();
1041 $supportedOps = array( 'create', 'store', 'copy', 'move', 'delete', 'null' );
1042 $async = ( $this->parallelize
=== 'implicit' );
1043 $maxConcurrency = $this->concurrency
; // throttle
1045 $statuses = array(); // array of (index => Status)
1046 $fileOpHandles = array(); // list of (index => handle) arrays
1047 $curFileOpHandles = array(); // current handle batch
1048 // Perform the sync-only ops and build up op handles for the async ops...
1049 foreach ( $ops as $index => $params ) {
1050 if ( !in_array( $params['op'], $supportedOps ) ) {
1051 wfProfileOut( __METHOD__
. '-' . $this->name
);
1052 wfProfileOut( __METHOD__
);
1053 throw new MWException( "Operation '{$params['op']}' is not supported." );
1055 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1056 $subStatus = $this->$method( array( 'async' => $async ) +
$params );
1057 if ( $subStatus->value
instanceof FileBackendStoreOpHandle
) { // async
1058 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1059 $fileOpHandles[] = $curFileOpHandles; // push this batch
1060 $curFileOpHandles = array();
1062 $curFileOpHandles[$index] = $subStatus->value
; // keep index
1063 } else { // error or completed
1064 $statuses[$index] = $subStatus; // keep index
1067 if ( count( $curFileOpHandles ) ) {
1068 $fileOpHandles[] = $curFileOpHandles; // last batch
1070 // Do all the async ops that can be done concurrently...
1071 foreach ( $fileOpHandles as $fileHandleBatch ) {
1072 $statuses = $statuses +
$this->executeOpHandlesInternal( $fileHandleBatch );
1074 // Marshall and merge all the responses...
1075 foreach ( $statuses as $index => $subStatus ) {
1076 $status->merge( $subStatus );
1077 if ( $subStatus->isOK() ) {
1078 $status->success
[$index] = true;
1079 ++
$status->successCount
;
1081 $status->success
[$index] = false;
1082 ++
$status->failCount
;
1086 wfProfileOut( __METHOD__
. '-' . $this->name
);
1087 wfProfileOut( __METHOD__
);
1092 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1093 * The resulting Status object fields will correspond
1094 * to the order in which the handles where given.
1096 * @param $handles Array List of FileBackendStoreOpHandle objects
1097 * @return Array Map of Status objects
1098 * @throws MWException
1100 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1101 wfProfileIn( __METHOD__
);
1102 wfProfileIn( __METHOD__
. '-' . $this->name
);
1103 foreach ( $fileOpHandles as $fileOpHandle ) {
1104 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle
) ) {
1105 throw new MWException( "Given a non-FileBackendStoreOpHandle object." );
1106 } elseif ( $fileOpHandle->backend
->getName() !== $this->getName() ) {
1107 throw new MWException( "Given a FileBackendStoreOpHandle for the wrong backend." );
1110 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1111 foreach ( $fileOpHandles as $fileOpHandle ) {
1112 $fileOpHandle->closeResources();
1114 wfProfileOut( __METHOD__
. '-' . $this->name
);
1115 wfProfileOut( __METHOD__
);
1120 * @see FileBackendStore::executeOpHandlesInternal()
1121 * @return Array List of corresponding Status objects
1123 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1124 foreach ( $fileOpHandles as $fileOpHandle ) { // OK if empty
1125 throw new MWException( "This backend supports no asynchronous operations." );
1131 * @see FileBackend::preloadCache()
1133 final public function preloadCache( array $paths ) {
1134 $fullConts = array(); // full container names
1135 foreach ( $paths as $path ) {
1136 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1137 $fullConts[] = $fullCont;
1139 // Load from the persistent file and container caches
1140 $this->primeContainerCache( $fullConts );
1141 $this->primeFileCache( $paths );
1145 * @see FileBackend::clearCache()
1147 final public function clearCache( array $paths = null ) {
1148 if ( is_array( $paths ) ) {
1149 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1150 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1152 if ( $paths === null ) {
1153 $this->cheapCache
->clear();
1154 $this->expensiveCache
->clear();
1156 foreach ( $paths as $path ) {
1157 $this->cheapCache
->clear( $path );
1158 $this->expensiveCache
->clear( $path );
1161 $this->doClearCache( $paths );
1165 * Clears any additional stat caches for storage paths
1167 * @see FileBackend::clearCache()
1169 * @param $paths Array Storage paths (optional)
1172 protected function doClearCache( array $paths = null ) {}
1175 * Is this a key/value store where directories are just virtual?
1176 * Virtual directories exists in so much as files exists that are
1177 * prefixed with the directory path followed by a forward slash.
1181 abstract protected function directoriesAreVirtual();
1184 * Check if a container name is valid.
1185 * This checks for for length and illegal characters.
1187 * @param $container string
1190 final protected static function isValidContainerName( $container ) {
1191 // This accounts for Swift and S3 restrictions while leaving room
1192 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1193 // This disallows directory separators or traversal characters.
1194 // Note that matching strings URL encode to the same string;
1195 // in Swift, the length restriction is *after* URL encoding.
1196 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1200 * Splits a storage path into an internal container name,
1201 * an internal relative file name, and a container shard suffix.
1202 * Any shard suffix is already appended to the internal container name.
1203 * This also checks that the storage path is valid and within this backend.
1205 * If the container is sharded but a suffix could not be determined,
1206 * this means that the path can only refer to a directory and can only
1207 * be scanned by looking in all the container shards.
1209 * @param $storagePath string
1210 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1212 final protected function resolveStoragePath( $storagePath ) {
1213 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1214 if ( $backend === $this->name
) { // must be for this backend
1215 $relPath = self
::normalizeContainerPath( $relPath );
1216 if ( $relPath !== null ) {
1217 // Get shard for the normalized path if this container is sharded
1218 $cShard = $this->getContainerShard( $container, $relPath );
1219 // Validate and sanitize the relative path (backend-specific)
1220 $relPath = $this->resolveContainerPath( $container, $relPath );
1221 if ( $relPath !== null ) {
1222 // Prepend any wiki ID prefix to the container name
1223 $container = $this->fullContainerName( $container );
1224 if ( self
::isValidContainerName( $container ) ) {
1225 // Validate and sanitize the container name (backend-specific)
1226 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1227 if ( $container !== null ) {
1228 return array( $container, $relPath, $cShard );
1234 return array( null, null, null );
1238 * Like resolveStoragePath() except null values are returned if
1239 * the container is sharded and the shard could not be determined.
1241 * @see FileBackendStore::resolveStoragePath()
1243 * @param $storagePath string
1244 * @return Array (container, path) or (null, null) if invalid
1246 final protected function resolveStoragePathReal( $storagePath ) {
1247 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1248 if ( $cShard !== null ) {
1249 return array( $container, $relPath );
1251 return array( null, null );
1255 * Get the container name shard suffix for a given path.
1256 * Any empty suffix means the container is not sharded.
1258 * @param $container string Container name
1259 * @param $relPath string Storage path relative to the container
1260 * @return string|null Returns null if shard could not be determined
1262 final protected function getContainerShard( $container, $relPath ) {
1263 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1264 if ( $levels == 1 ||
$levels == 2 ) {
1265 // Hash characters are either base 16 or 36
1266 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1267 // Get a regex that represents the shard portion of paths.
1268 // The concatenation of the captures gives us the shard.
1269 if ( $levels === 1 ) { // 16 or 36 shards per container
1270 $hashDirRegex = '(' . $char . ')';
1271 } else { // 256 or 1296 shards per container
1272 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1273 $hashDirRegex = $char . '/(' . $char . '{2})';
1274 } else { // short hash dir format (e.g. "a/b/c")
1275 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1278 // Allow certain directories to be above the hash dirs so as
1279 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1280 // They must be 2+ chars to avoid any hash directory ambiguity.
1282 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1283 return '.' . implode( '', array_slice( $m, 1 ) );
1285 return null; // failed to match
1287 return ''; // no sharding
1291 * Check if a storage path maps to a single shard.
1292 * Container dirs like "a", where the container shards on "x/xy",
1293 * can reside on several shards. Such paths are tricky to handle.
1295 * @param $storagePath string Storage path
1298 final public function isSingleShardPathInternal( $storagePath ) {
1299 list( $c, $r, $shard ) = $this->resolveStoragePath( $storagePath );
1300 return ( $shard !== null );
1304 * Get the sharding config for a container.
1305 * If greater than 0, then all file storage paths within
1306 * the container are required to be hashed accordingly.
1308 * @param $container string
1309 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
1311 final protected function getContainerHashLevels( $container ) {
1312 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1313 $config = $this->shardViaHashLevels
[$container];
1314 $hashLevels = (int)$config['levels'];
1315 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1316 $hashBase = (int)$config['base'];
1317 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1318 return array( $hashLevels, $hashBase, $config['repeat'] );
1322 return array( 0, 0, false ); // no sharding
1326 * Get a list of full container shard suffixes for a container
1328 * @param $container string
1331 final protected function getContainerSuffixes( $container ) {
1333 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1334 if ( $digits > 0 ) {
1335 $numShards = pow( $base, $digits );
1336 for ( $index = 0; $index < $numShards; $index++
) {
1337 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1344 * Get the full container name, including the wiki ID prefix
1346 * @param $container string
1349 final protected function fullContainerName( $container ) {
1350 if ( $this->wikiId
!= '' ) {
1351 return "{$this->wikiId}-$container";
1358 * Resolve a container name, checking if it's allowed by the backend.
1359 * This is intended for internal use, such as encoding illegal chars.
1360 * Subclasses can override this to be more restrictive.
1362 * @param $container string
1363 * @return string|null
1365 protected function resolveContainerName( $container ) {
1370 * Resolve a relative storage path, checking if it's allowed by the backend.
1371 * This is intended for internal use, such as encoding illegal chars or perhaps
1372 * getting absolute paths (e.g. FS based backends). Note that the relative path
1373 * may be the empty string (e.g. the path is simply to the container).
1375 * @param $container string Container name
1376 * @param $relStoragePath string Storage path relative to the container
1377 * @return string|null Path or null if not valid
1379 protected function resolveContainerPath( $container, $relStoragePath ) {
1380 return $relStoragePath;
1384 * Get the cache key for a container
1386 * @param $container string Resolved container name
1389 private function containerCacheKey( $container ) {
1390 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1394 * Set the cached info for a container
1396 * @param $container string Resolved container name
1397 * @param $val mixed Information to cache
1399 final protected function setContainerCache( $container, $val ) {
1400 $this->memCache
->add( $this->containerCacheKey( $container ), $val, 14*86400 );
1404 * Delete the cached info for a container.
1405 * The cache key is salted for a while to prevent race conditions.
1407 * @param $container string Resolved container name
1409 final protected function deleteContainerCache( $container ) {
1410 if ( !$this->memCache
->set( $this->containerCacheKey( $container ), 'PURGED', 300 ) ) {
1411 trigger_error( "Unable to delete stat cache for container $container." );
1416 * Do a batch lookup from cache for container stats for all containers
1417 * used in a list of container names, storage paths, or FileOp objects.
1419 * @param $items Array
1422 final protected function primeContainerCache( array $items ) {
1423 wfProfileIn( __METHOD__
);
1424 wfProfileIn( __METHOD__
. '-' . $this->name
);
1426 $paths = array(); // list of storage paths
1427 $contNames = array(); // (cache key => resolved container name)
1428 // Get all the paths/containers from the items...
1429 foreach ( $items as $item ) {
1430 if ( $item instanceof FileOp
) {
1431 $paths = array_merge( $paths, $item->storagePathsRead() );
1432 $paths = array_merge( $paths, $item->storagePathsChanged() );
1433 } elseif ( self
::isStoragePath( $item ) ) {
1435 } elseif ( is_string( $item ) ) { // full container name
1436 $contNames[$this->containerCacheKey( $item )] = $item;
1439 // Get all the corresponding cache keys for paths...
1440 foreach ( $paths as $path ) {
1441 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1442 if ( $fullCont !== null ) { // valid path for this backend
1443 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1447 $contInfo = array(); // (resolved container name => cache value)
1448 // Get all cache entries for these container cache keys...
1449 $values = $this->memCache
->getMulti( array_keys( $contNames ) );
1450 foreach ( $values as $cacheKey => $val ) {
1451 $contInfo[$contNames[$cacheKey]] = $val;
1454 // Populate the container process cache for the backend...
1455 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1457 wfProfileOut( __METHOD__
. '-' . $this->name
);
1458 wfProfileOut( __METHOD__
);
1462 * Fill the backend-specific process cache given an array of
1463 * resolved container names and their corresponding cached info.
1464 * Only containers that actually exist should appear in the map.
1466 * @param $containerInfo Array Map of resolved container names to cached info
1469 protected function doPrimeContainerCache( array $containerInfo ) {}
1472 * Get the cache key for a file path
1474 * @param $path string Storage path
1477 private function fileCacheKey( $path ) {
1478 return wfMemcKey( 'backend', $this->getName(), 'file', sha1( $path ) );
1482 * Set the cached stat info for a file path.
1483 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1484 * salting for the case when a file is created at a path were there was none before.
1486 * @param $path string Storage path
1487 * @param $val mixed Information to cache
1489 final protected function setFileCache( $path, $val ) {
1490 $this->memCache
->add( $this->fileCacheKey( $path ), $val, 7*86400 );
1494 * Delete the cached stat info for a file path.
1495 * The cache key is salted for a while to prevent race conditions.
1497 * @param $path string Storage path
1499 final protected function deleteFileCache( $path ) {
1500 if ( !$this->memCache
->set( $this->fileCacheKey( $path ), 'PURGED', 300 ) ) {
1501 trigger_error( "Unable to delete stat cache for file $path." );
1506 * Do a batch lookup from cache for file stats for all paths
1507 * used in a list of storage paths or FileOp objects.
1509 * @param $items Array List of storage paths or FileOps
1512 final protected function primeFileCache( array $items ) {
1513 wfProfileIn( __METHOD__
);
1514 wfProfileIn( __METHOD__
. '-' . $this->name
);
1516 $paths = array(); // list of storage paths
1517 $pathNames = array(); // (cache key => storage path)
1518 // Get all the paths/containers from the items...
1519 foreach ( $items as $item ) {
1520 if ( $item instanceof FileOp
) {
1521 $paths = array_merge( $paths, $item->storagePathsRead() );
1522 $paths = array_merge( $paths, $item->storagePathsChanged() );
1523 } elseif ( self
::isStoragePath( $item ) ) {
1527 // Get all the corresponding cache keys for paths...
1528 foreach ( $paths as $path ) {
1529 list( $cont, $rel, $s ) = $this->resolveStoragePath( $path );
1530 if ( $rel !== null ) { // valid path for this backend
1531 $pathNames[$this->fileCacheKey( $path )] = $path;
1534 // Get all cache entries for these container cache keys...
1535 $values = $this->memCache
->getMulti( array_keys( $pathNames ) );
1536 foreach ( $values as $cacheKey => $val ) {
1537 if ( is_array( $val ) ) {
1538 $path = $pathNames[$cacheKey];
1539 $this->cheapCache
->set( $path, 'stat', $val );
1540 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1541 $this->cheapCache
->set( $path, 'sha1',
1542 array( 'hash' => $val['sha1'], 'latest' => $val['latest'] ) );
1547 wfProfileOut( __METHOD__
. '-' . $this->name
);
1548 wfProfileOut( __METHOD__
);
1552 * Set the 'concurrency' option from a list of operation options
1554 * @param $opts array Map of operation options
1557 final protected function setConcurrencyFlags( array $opts ) {
1558 $opts['concurrency'] = 1; // off
1559 if ( $this->parallelize
=== 'implicit' ) {
1560 if ( !isset( $opts['parallelize'] ) ||
$opts['parallelize'] ) {
1561 $opts['concurrency'] = $this->concurrency
;
1563 } elseif ( $this->parallelize
=== 'explicit' ) {
1564 if ( !empty( $opts['parallelize'] ) ) {
1565 $opts['concurrency'] = $this->concurrency
;
1573 * FileBackendStore helper class for performing asynchronous file operations.
1575 * For example, calling FileBackendStore::createInternal() with the "async"
1576 * param flag may result in a Status that contains this object as a value.
1577 * This class is largely backend-specific and is mostly just "magic" to be
1578 * passed to FileBackendStore::executeOpHandlesInternal().
1580 abstract class FileBackendStoreOpHandle
{
1582 public $params = array(); // params to caller functions
1583 /** @var FileBackendStore */
1586 public $resourcesToClose = array();
1588 public $call; // string; name that identifies the function called
1591 * Close all open file handles
1595 public function closeResources() {
1596 array_map( 'fclose', $this->resourcesToClose
);
1601 * FileBackendStore helper function to handle listings that span container shards.
1602 * Do not use this class from places outside of FileBackendStore.
1604 * @ingroup FileBackend
1606 abstract class FileBackendStoreShardListIterator
implements Iterator
{
1607 /** @var FileBackendStore */
1612 protected $shardSuffixes;
1613 protected $container; // string; full container name
1614 protected $directory; // string; resolved relative path
1616 /** @var Traversable */
1618 protected $curShard = 0; // integer
1619 protected $pos = 0; // integer
1622 protected $multiShardPaths = array(); // (rel path => 1)
1625 * @param $backend FileBackendStore
1626 * @param $container string Full storage container name
1627 * @param $dir string Storage directory relative to container
1628 * @param $suffixes Array List of container shard suffixes
1629 * @param $params Array
1631 public function __construct(
1632 FileBackendStore
$backend, $container, $dir, array $suffixes, array $params
1634 $this->backend
= $backend;
1635 $this->container
= $container;
1636 $this->directory
= $dir;
1637 $this->shardSuffixes
= $suffixes;
1638 $this->params
= $params;
1642 * @see Iterator::key()
1645 public function key() {
1650 * @see Iterator::valid()
1653 public function valid() {
1654 if ( $this->iter
instanceof Iterator
) {
1655 return $this->iter
->valid();
1656 } elseif ( is_array( $this->iter
) ) {
1657 return ( current( $this->iter
) !== false ); // no paths can have this value
1659 return false; // some failure?
1663 * @see Iterator::current()
1664 * @return string|bool String or false
1666 public function current() {
1667 return ( $this->iter
instanceof Iterator
)
1668 ?
$this->iter
->current()
1669 : current( $this->iter
);
1673 * @see Iterator::next()
1676 public function next() {
1678 ( $this->iter
instanceof Iterator
) ?
$this->iter
->next() : next( $this->iter
);
1680 $continue = false; // keep scanning shards?
1681 $this->filterViaNext(); // filter out duplicates
1682 // Find the next non-empty shard if no elements are left
1683 if ( !$this->valid() ) {
1684 $this->nextShardIteratorIfNotValid();
1685 $continue = $this->valid(); // re-filter unless we ran out of shards
1687 } while ( $continue );
1691 * @see Iterator::rewind()
1694 public function rewind() {
1696 $this->curShard
= 0;
1697 $this->setIteratorFromCurrentShard();
1699 $continue = false; // keep scanning shards?
1700 $this->filterViaNext(); // filter out duplicates
1701 // Find the next non-empty shard if no elements are left
1702 if ( !$this->valid() ) {
1703 $this->nextShardIteratorIfNotValid();
1704 $continue = $this->valid(); // re-filter unless we ran out of shards
1706 } while ( $continue );
1710 * Filter out duplicate items by advancing to the next ones
1712 protected function filterViaNext() {
1713 while ( $this->valid() ) {
1714 $rel = $this->iter
->current(); // path relative to given directory
1715 $path = $this->params
['dir'] . "/{$rel}"; // full storage path
1716 if ( $this->backend
->isSingleShardPathInternal( $path ) ) {
1717 break; // path is only on one shard; no issue with duplicates
1718 } elseif ( isset( $this->multiShardPaths
[$rel] ) ) {
1719 // Don't keep listing paths that are on multiple shards
1720 ( $this->iter
instanceof Iterator
) ?
$this->iter
->next() : next( $this->iter
);
1722 $this->multiShardPaths
[$rel] = 1;
1729 * If the list iterator for this container shard is out of items,
1730 * then move on to the next container that has items.
1731 * If there are none, then it advances to the last container.
1733 protected function nextShardIteratorIfNotValid() {
1734 while ( !$this->valid() && ++
$this->curShard
< count( $this->shardSuffixes
) ) {
1735 $this->setIteratorFromCurrentShard();
1740 * Set the list iterator to that of the current container shard
1742 protected function setIteratorFromCurrentShard() {
1743 $this->iter
= $this->listFromShard(
1744 $this->container
. $this->shardSuffixes
[$this->curShard
],
1745 $this->directory
, $this->params
);
1746 // Start loading results so that current() works
1747 if ( $this->iter
) {
1748 ( $this->iter
instanceof Iterator
) ?
$this->iter
->rewind() : reset( $this->iter
);
1753 * Get the list for a given container shard
1755 * @param $container string Resolved container name
1756 * @param $dir string Resolved path relative to container
1757 * @param $params Array
1758 * @return Traversable|Array|null
1760 abstract protected function listFromShard( $container, $dir, array $params );
1764 * Iterator for listing directories
1766 class FileBackendStoreShardDirIterator
extends FileBackendStoreShardListIterator
{
1768 * @see FileBackendStoreShardListIterator::listFromShard()
1769 * @return Array|null|Traversable
1771 protected function listFromShard( $container, $dir, array $params ) {
1772 return $this->backend
->getDirectoryListInternal( $container, $dir, $params );
1777 * Iterator for listing regular files
1779 class FileBackendStoreShardFileIterator
extends FileBackendStoreShardListIterator
{
1781 * @see FileBackendStoreShardListIterator::listFromShard()
1782 * @return Array|null|Traversable
1784 protected function listFromShard( $container, $dir, array $params ) {
1785 return $this->backend
->getFileListInternal( $container, $dir, $params );