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(), 'rb' );
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::getLocalReferenceMulti()
726 final public function getLocalReferenceMulti( array $params ) {
727 wfProfileIn( __METHOD__
);
728 wfProfileIn( __METHOD__
. '-' . $this->name
);
730 $params = $this->setConcurrencyFlags( $params );
732 $fsFiles = array(); // (path => FSFile)
733 $latest = !empty( $params['latest'] ); // use latest data?
734 // Reuse any files already in process cache...
735 foreach ( $params['srcs'] as $src ) {
736 $path = self
::normalizeStoragePath( $src );
737 if ( $path === null ) {
738 $fsFiles[$src] = null; // invalid storage path
739 } elseif ( $this->expensiveCache
->has( $path, 'localRef' ) ) {
740 $val = $this->expensiveCache
->get( $path, 'localRef' );
741 // If we want the latest data, check that this cached
742 // value was in fact fetched with the latest available data.
743 if ( !$latest ||
$val['latest'] ) {
744 $fsFiles[$src] = $val['object'];
748 // Fetch local references of any remaning files...
749 $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
750 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
751 $fsFiles[$path] = $fsFile;
752 if ( $fsFile ) { // update the process cache...
753 $this->expensiveCache
->set( $path, 'localRef',
754 array( 'object' => $fsFile, 'latest' => $latest ) );
758 wfProfileOut( __METHOD__
. '-' . $this->name
);
759 wfProfileOut( __METHOD__
);
764 * @see FileBackendStore::getLocalReferenceMulti()
767 protected function doGetLocalReferenceMulti( array $params ) {
768 return $this->doGetLocalCopyMulti( $params );
772 * @see FileBackend::getLocalCopyMulti()
775 final public function getLocalCopyMulti( array $params ) {
776 wfProfileIn( __METHOD__
);
777 wfProfileIn( __METHOD__
. '-' . $this->name
);
779 $params = $this->setConcurrencyFlags( $params );
780 $tmpFiles = $this->doGetLocalCopyMulti( $params );
782 wfProfileOut( __METHOD__
. '-' . $this->name
);
783 wfProfileOut( __METHOD__
);
788 * @see FileBackendStore::getLocalCopyMulti()
791 abstract protected function doGetLocalCopyMulti( array $params );
794 * @see FileBackend::streamFile()
797 final public function streamFile( array $params ) {
798 wfProfileIn( __METHOD__
);
799 wfProfileIn( __METHOD__
. '-' . $this->name
);
800 $status = Status
::newGood();
802 $info = $this->getFileStat( $params );
803 if ( !$info ) { // let StreamFile handle the 404
804 $status->fatal( 'backend-fail-notexists', $params['src'] );
807 // Set output buffer and HTTP headers for stream
808 $extraHeaders = isset( $params['headers'] ) ?
$params['headers'] : array();
809 $res = StreamFile
::prepareForStream( $params['src'], $info, $extraHeaders );
810 if ( $res == StreamFile
::NOT_MODIFIED
) {
811 // do nothing; client cache is up to date
812 } elseif ( $res == StreamFile
::READY_STREAM
) {
813 wfProfileIn( __METHOD__
. '-send' );
814 wfProfileIn( __METHOD__
. '-send-' . $this->name
);
815 $status = $this->doStreamFile( $params );
816 wfProfileOut( __METHOD__
. '-send-' . $this->name
);
817 wfProfileOut( __METHOD__
. '-send' );
819 $status->fatal( 'backend-fail-stream', $params['src'] );
822 wfProfileOut( __METHOD__
. '-' . $this->name
);
823 wfProfileOut( __METHOD__
);
828 * @see FileBackendStore::streamFile()
831 protected function doStreamFile( array $params ) {
832 $status = Status
::newGood();
834 $fsFile = $this->getLocalReference( $params );
836 $status->fatal( 'backend-fail-stream', $params['src'] );
837 } elseif ( !readfile( $fsFile->getPath() ) ) {
838 $status->fatal( 'backend-fail-stream', $params['src'] );
845 * @see FileBackend::directoryExists()
848 final public function directoryExists( array $params ) {
849 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
850 if ( $dir === null ) {
851 return false; // invalid storage path
853 if ( $shard !== null ) { // confined to a single container/shard
854 return $this->doDirectoryExists( $fullCont, $dir, $params );
855 } else { // directory is on several shards
856 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
857 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
858 $res = false; // response
859 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
860 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
864 } elseif ( $exists === null ) { // error?
865 $res = null; // if we don't find anything, it is indeterminate
873 * @see FileBackendStore::directoryExists()
875 * @param $container string Resolved container name
876 * @param $dir string Resolved path relative to container
877 * @param $params Array
880 abstract protected function doDirectoryExists( $container, $dir, array $params );
883 * @see FileBackend::getDirectoryList()
884 * @return Traversable|Array|null Returns null on failure
886 final public function getDirectoryList( array $params ) {
887 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
888 if ( $dir === null ) { // invalid storage path
891 if ( $shard !== null ) {
892 // File listing is confined to a single container/shard
893 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
895 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
896 // File listing spans multiple containers/shards
897 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
898 return new FileBackendStoreShardDirIterator( $this,
899 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
904 * Do not call this function from places outside FileBackend
906 * @see FileBackendStore::getDirectoryList()
908 * @param $container string Resolved container name
909 * @param $dir string Resolved path relative to container
910 * @param $params Array
911 * @return Traversable|Array|null Returns null on failure
913 abstract public function getDirectoryListInternal( $container, $dir, array $params );
916 * @see FileBackend::getFileList()
917 * @return Traversable|Array|null Returns null on failure
919 final public function getFileList( array $params ) {
920 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
921 if ( $dir === null ) { // invalid storage path
924 if ( $shard !== null ) {
925 // File listing is confined to a single container/shard
926 return $this->getFileListInternal( $fullCont, $dir, $params );
928 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
929 // File listing spans multiple containers/shards
930 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
931 return new FileBackendStoreShardFileIterator( $this,
932 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
937 * Do not call this function from places outside FileBackend
939 * @see FileBackendStore::getFileList()
941 * @param $container string Resolved container name
942 * @param $dir string Resolved path relative to container
943 * @param $params Array
944 * @return Traversable|Array|null Returns null on failure
946 abstract public function getFileListInternal( $container, $dir, array $params );
949 * Return a list of FileOp objects from a list of operations.
950 * Do not call this function from places outside FileBackend.
952 * The result must have the same number of items as the input.
953 * An exception is thrown if an unsupported operation is requested.
955 * @param $ops Array Same format as doOperations()
956 * @return Array List of FileOp objects
957 * @throws MWException
959 final public function getOperationsInternal( array $ops ) {
960 $supportedOps = array(
961 'store' => 'StoreFileOp',
962 'copy' => 'CopyFileOp',
963 'move' => 'MoveFileOp',
964 'delete' => 'DeleteFileOp',
965 'create' => 'CreateFileOp',
966 'null' => 'NullFileOp'
969 $performOps = array(); // array of FileOp objects
970 // Build up ordered array of FileOps...
971 foreach ( $ops as $operation ) {
972 $opName = $operation['op'];
973 if ( isset( $supportedOps[$opName] ) ) {
974 $class = $supportedOps[$opName];
975 // Get params for this operation
976 $params = $operation;
977 // Append the FileOp class
978 $performOps[] = new $class( $this, $params );
980 throw new MWException( "Operation '$opName' is not supported." );
988 * Get a list of storage paths to lock for a list of operations
989 * Returns an array with 'sh' (shared) and 'ex' (exclusive) keys,
990 * each corresponding to a list of storage paths to be locked.
992 * @param $performOps Array List of FileOp objects
993 * @return Array ('sh' => list of paths, 'ex' => list of paths)
995 final public function getPathsToLockForOpsInternal( array $performOps ) {
996 // Build up a list of files to lock...
997 $paths = array( 'sh' => array(), 'ex' => array() );
998 foreach ( $performOps as $fileOp ) {
999 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1000 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1002 // Optimization: if doing an EX lock anyway, don't also set an SH one
1003 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1004 // Get a shared lock on the parent directory of each path changed
1005 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1011 * @see FileBackend::getScopedLocksForOps()
1014 public function getScopedLocksForOps( array $ops, Status
$status ) {
1015 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1017 $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status ),
1018 $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status )
1023 * @see FileBackend::doOperationsInternal()
1026 final protected function doOperationsInternal( array $ops, array $opts ) {
1027 wfProfileIn( __METHOD__
);
1028 wfProfileIn( __METHOD__
. '-' . $this->name
);
1029 $status = Status
::newGood();
1031 // Build up a list of FileOps...
1032 $performOps = $this->getOperationsInternal( $ops );
1034 // Acquire any locks as needed...
1035 if ( empty( $opts['nonLocking'] ) ) {
1036 // Build up a list of files to lock...
1037 $paths = $this->getPathsToLockForOpsInternal( $performOps );
1038 // Try to lock those files for the scope of this function...
1039 $scopeLockS = $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status );
1040 $scopeLockE = $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status );
1041 if ( !$status->isOK() ) {
1042 wfProfileOut( __METHOD__
. '-' . $this->name
);
1043 wfProfileOut( __METHOD__
);
1044 return $status; // abort
1048 // Clear any file cache entries (after locks acquired)
1049 if ( empty( $opts['preserveCache'] ) ) {
1050 $this->clearCache();
1053 // Load from the persistent file and container caches
1054 $this->primeFileCache( $performOps );
1055 $this->primeContainerCache( $performOps );
1057 // Actually attempt the operation batch...
1058 $opts = $this->setConcurrencyFlags( $opts );
1059 $subStatus = FileOpBatch
::attempt( $performOps, $opts, $this->fileJournal
);
1061 // Merge errors into status fields
1062 $status->merge( $subStatus );
1063 $status->success
= $subStatus->success
; // not done in merge()
1065 wfProfileOut( __METHOD__
. '-' . $this->name
);
1066 wfProfileOut( __METHOD__
);
1071 * @see FileBackend::doQuickOperationsInternal()
1073 * @throws MWException
1075 final protected function doQuickOperationsInternal( array $ops ) {
1076 wfProfileIn( __METHOD__
);
1077 wfProfileIn( __METHOD__
. '-' . $this->name
);
1078 $status = Status
::newGood();
1080 $supportedOps = array( 'create', 'store', 'copy', 'move', 'delete', 'null' );
1081 $async = ( $this->parallelize
=== 'implicit' );
1082 $maxConcurrency = $this->concurrency
; // throttle
1084 $statuses = array(); // array of (index => Status)
1085 $fileOpHandles = array(); // list of (index => handle) arrays
1086 $curFileOpHandles = array(); // current handle batch
1087 // Perform the sync-only ops and build up op handles for the async ops...
1088 foreach ( $ops as $index => $params ) {
1089 if ( !in_array( $params['op'], $supportedOps ) ) {
1090 wfProfileOut( __METHOD__
. '-' . $this->name
);
1091 wfProfileOut( __METHOD__
);
1092 throw new MWException( "Operation '{$params['op']}' is not supported." );
1094 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1095 $subStatus = $this->$method( array( 'async' => $async ) +
$params );
1096 if ( $subStatus->value
instanceof FileBackendStoreOpHandle
) { // async
1097 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1098 $fileOpHandles[] = $curFileOpHandles; // push this batch
1099 $curFileOpHandles = array();
1101 $curFileOpHandles[$index] = $subStatus->value
; // keep index
1102 } else { // error or completed
1103 $statuses[$index] = $subStatus; // keep index
1106 if ( count( $curFileOpHandles ) ) {
1107 $fileOpHandles[] = $curFileOpHandles; // last batch
1109 // Do all the async ops that can be done concurrently...
1110 foreach ( $fileOpHandles as $fileHandleBatch ) {
1111 $statuses = $statuses +
$this->executeOpHandlesInternal( $fileHandleBatch );
1113 // Marshall and merge all the responses...
1114 foreach ( $statuses as $index => $subStatus ) {
1115 $status->merge( $subStatus );
1116 if ( $subStatus->isOK() ) {
1117 $status->success
[$index] = true;
1118 ++
$status->successCount
;
1120 $status->success
[$index] = false;
1121 ++
$status->failCount
;
1125 wfProfileOut( __METHOD__
. '-' . $this->name
);
1126 wfProfileOut( __METHOD__
);
1131 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1132 * The resulting Status object fields will correspond
1133 * to the order in which the handles where given.
1135 * @param $handles Array List of FileBackendStoreOpHandle objects
1136 * @return Array Map of Status objects
1137 * @throws MWException
1139 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1140 wfProfileIn( __METHOD__
);
1141 wfProfileIn( __METHOD__
. '-' . $this->name
);
1142 foreach ( $fileOpHandles as $fileOpHandle ) {
1143 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle
) ) {
1144 throw new MWException( "Given a non-FileBackendStoreOpHandle object." );
1145 } elseif ( $fileOpHandle->backend
->getName() !== $this->getName() ) {
1146 throw new MWException( "Given a FileBackendStoreOpHandle for the wrong backend." );
1149 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1150 foreach ( $fileOpHandles as $fileOpHandle ) {
1151 $fileOpHandle->closeResources();
1153 wfProfileOut( __METHOD__
. '-' . $this->name
);
1154 wfProfileOut( __METHOD__
);
1159 * @see FileBackendStore::executeOpHandlesInternal()
1160 * @return Array List of corresponding Status objects
1162 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1163 foreach ( $fileOpHandles as $fileOpHandle ) { // OK if empty
1164 throw new MWException( "This backend supports no asynchronous operations." );
1170 * @see FileBackend::preloadCache()
1172 final public function preloadCache( array $paths ) {
1173 $fullConts = array(); // full container names
1174 foreach ( $paths as $path ) {
1175 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1176 $fullConts[] = $fullCont;
1178 // Load from the persistent file and container caches
1179 $this->primeContainerCache( $fullConts );
1180 $this->primeFileCache( $paths );
1184 * @see FileBackend::clearCache()
1186 final public function clearCache( array $paths = null ) {
1187 if ( is_array( $paths ) ) {
1188 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1189 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1191 if ( $paths === null ) {
1192 $this->cheapCache
->clear();
1193 $this->expensiveCache
->clear();
1195 foreach ( $paths as $path ) {
1196 $this->cheapCache
->clear( $path );
1197 $this->expensiveCache
->clear( $path );
1200 $this->doClearCache( $paths );
1204 * Clears any additional stat caches for storage paths
1206 * @see FileBackend::clearCache()
1208 * @param $paths Array Storage paths (optional)
1211 protected function doClearCache( array $paths = null ) {}
1214 * Is this a key/value store where directories are just virtual?
1215 * Virtual directories exists in so much as files exists that are
1216 * prefixed with the directory path followed by a forward slash.
1220 abstract protected function directoriesAreVirtual();
1223 * Check if a container name is valid.
1224 * This checks for for length and illegal characters.
1226 * @param $container string
1229 final protected static function isValidContainerName( $container ) {
1230 // This accounts for Swift and S3 restrictions while leaving room
1231 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1232 // This disallows directory separators or traversal characters.
1233 // Note that matching strings URL encode to the same string;
1234 // in Swift, the length restriction is *after* URL encoding.
1235 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1239 * Splits a storage path into an internal container name,
1240 * an internal relative file name, and a container shard suffix.
1241 * Any shard suffix is already appended to the internal container name.
1242 * This also checks that the storage path is valid and within this backend.
1244 * If the container is sharded but a suffix could not be determined,
1245 * this means that the path can only refer to a directory and can only
1246 * be scanned by looking in all the container shards.
1248 * @param $storagePath string
1249 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1251 final protected function resolveStoragePath( $storagePath ) {
1252 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1253 if ( $backend === $this->name
) { // must be for this backend
1254 $relPath = self
::normalizeContainerPath( $relPath );
1255 if ( $relPath !== null ) {
1256 // Get shard for the normalized path if this container is sharded
1257 $cShard = $this->getContainerShard( $container, $relPath );
1258 // Validate and sanitize the relative path (backend-specific)
1259 $relPath = $this->resolveContainerPath( $container, $relPath );
1260 if ( $relPath !== null ) {
1261 // Prepend any wiki ID prefix to the container name
1262 $container = $this->fullContainerName( $container );
1263 if ( self
::isValidContainerName( $container ) ) {
1264 // Validate and sanitize the container name (backend-specific)
1265 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1266 if ( $container !== null ) {
1267 return array( $container, $relPath, $cShard );
1273 return array( null, null, null );
1277 * Like resolveStoragePath() except null values are returned if
1278 * the container is sharded and the shard could not be determined.
1280 * @see FileBackendStore::resolveStoragePath()
1282 * @param $storagePath string
1283 * @return Array (container, path) or (null, null) if invalid
1285 final protected function resolveStoragePathReal( $storagePath ) {
1286 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1287 if ( $cShard !== null ) {
1288 return array( $container, $relPath );
1290 return array( null, null );
1294 * Get the container name shard suffix for a given path.
1295 * Any empty suffix means the container is not sharded.
1297 * @param $container string Container name
1298 * @param $relPath string Storage path relative to the container
1299 * @return string|null Returns null if shard could not be determined
1301 final protected function getContainerShard( $container, $relPath ) {
1302 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1303 if ( $levels == 1 ||
$levels == 2 ) {
1304 // Hash characters are either base 16 or 36
1305 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1306 // Get a regex that represents the shard portion of paths.
1307 // The concatenation of the captures gives us the shard.
1308 if ( $levels === 1 ) { // 16 or 36 shards per container
1309 $hashDirRegex = '(' . $char . ')';
1310 } else { // 256 or 1296 shards per container
1311 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1312 $hashDirRegex = $char . '/(' . $char . '{2})';
1313 } else { // short hash dir format (e.g. "a/b/c")
1314 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1317 // Allow certain directories to be above the hash dirs so as
1318 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1319 // They must be 2+ chars to avoid any hash directory ambiguity.
1321 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1322 return '.' . implode( '', array_slice( $m, 1 ) );
1324 return null; // failed to match
1326 return ''; // no sharding
1330 * Check if a storage path maps to a single shard.
1331 * Container dirs like "a", where the container shards on "x/xy",
1332 * can reside on several shards. Such paths are tricky to handle.
1334 * @param $storagePath string Storage path
1337 final public function isSingleShardPathInternal( $storagePath ) {
1338 list( $c, $r, $shard ) = $this->resolveStoragePath( $storagePath );
1339 return ( $shard !== null );
1343 * Get the sharding config for a container.
1344 * If greater than 0, then all file storage paths within
1345 * the container are required to be hashed accordingly.
1347 * @param $container string
1348 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
1350 final protected function getContainerHashLevels( $container ) {
1351 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1352 $config = $this->shardViaHashLevels
[$container];
1353 $hashLevels = (int)$config['levels'];
1354 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1355 $hashBase = (int)$config['base'];
1356 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1357 return array( $hashLevels, $hashBase, $config['repeat'] );
1361 return array( 0, 0, false ); // no sharding
1365 * Get a list of full container shard suffixes for a container
1367 * @param $container string
1370 final protected function getContainerSuffixes( $container ) {
1372 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1373 if ( $digits > 0 ) {
1374 $numShards = pow( $base, $digits );
1375 for ( $index = 0; $index < $numShards; $index++
) {
1376 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1383 * Get the full container name, including the wiki ID prefix
1385 * @param $container string
1388 final protected function fullContainerName( $container ) {
1389 if ( $this->wikiId
!= '' ) {
1390 return "{$this->wikiId}-$container";
1397 * Resolve a container name, checking if it's allowed by the backend.
1398 * This is intended for internal use, such as encoding illegal chars.
1399 * Subclasses can override this to be more restrictive.
1401 * @param $container string
1402 * @return string|null
1404 protected function resolveContainerName( $container ) {
1409 * Resolve a relative storage path, checking if it's allowed by the backend.
1410 * This is intended for internal use, such as encoding illegal chars or perhaps
1411 * getting absolute paths (e.g. FS based backends). Note that the relative path
1412 * may be the empty string (e.g. the path is simply to the container).
1414 * @param $container string Container name
1415 * @param $relStoragePath string Storage path relative to the container
1416 * @return string|null Path or null if not valid
1418 protected function resolveContainerPath( $container, $relStoragePath ) {
1419 return $relStoragePath;
1423 * Get the cache key for a container
1425 * @param $container string Resolved container name
1428 private function containerCacheKey( $container ) {
1429 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1433 * Set the cached info for a container
1435 * @param $container string Resolved container name
1436 * @param $val mixed Information to cache
1438 final protected function setContainerCache( $container, $val ) {
1439 $this->memCache
->add( $this->containerCacheKey( $container ), $val, 14*86400 );
1443 * Delete the cached info for a container.
1444 * The cache key is salted for a while to prevent race conditions.
1446 * @param $container string Resolved container name
1448 final protected function deleteContainerCache( $container ) {
1449 if ( !$this->memCache
->set( $this->containerCacheKey( $container ), 'PURGED', 300 ) ) {
1450 trigger_error( "Unable to delete stat cache for container $container." );
1455 * Do a batch lookup from cache for container stats for all containers
1456 * used in a list of container names, storage paths, or FileOp objects.
1458 * @param $items Array
1461 final protected function primeContainerCache( array $items ) {
1462 wfProfileIn( __METHOD__
);
1463 wfProfileIn( __METHOD__
. '-' . $this->name
);
1465 $paths = array(); // list of storage paths
1466 $contNames = array(); // (cache key => resolved container name)
1467 // Get all the paths/containers from the items...
1468 foreach ( $items as $item ) {
1469 if ( $item instanceof FileOp
) {
1470 $paths = array_merge( $paths, $item->storagePathsRead() );
1471 $paths = array_merge( $paths, $item->storagePathsChanged() );
1472 } elseif ( self
::isStoragePath( $item ) ) {
1474 } elseif ( is_string( $item ) ) { // full container name
1475 $contNames[$this->containerCacheKey( $item )] = $item;
1478 // Get all the corresponding cache keys for paths...
1479 foreach ( $paths as $path ) {
1480 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1481 if ( $fullCont !== null ) { // valid path for this backend
1482 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1486 $contInfo = array(); // (resolved container name => cache value)
1487 // Get all cache entries for these container cache keys...
1488 $values = $this->memCache
->getMulti( array_keys( $contNames ) );
1489 foreach ( $values as $cacheKey => $val ) {
1490 $contInfo[$contNames[$cacheKey]] = $val;
1493 // Populate the container process cache for the backend...
1494 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1496 wfProfileOut( __METHOD__
. '-' . $this->name
);
1497 wfProfileOut( __METHOD__
);
1501 * Fill the backend-specific process cache given an array of
1502 * resolved container names and their corresponding cached info.
1503 * Only containers that actually exist should appear in the map.
1505 * @param $containerInfo Array Map of resolved container names to cached info
1508 protected function doPrimeContainerCache( array $containerInfo ) {}
1511 * Get the cache key for a file path
1513 * @param $path string Storage path
1516 private function fileCacheKey( $path ) {
1517 return wfMemcKey( 'backend', $this->getName(), 'file', sha1( $path ) );
1521 * Set the cached stat info for a file path.
1522 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1523 * salting for the case when a file is created at a path were there was none before.
1525 * @param $path string Storage path
1526 * @param $val mixed Information to cache
1528 final protected function setFileCache( $path, $val ) {
1529 $this->memCache
->add( $this->fileCacheKey( $path ), $val, 7*86400 );
1533 * Delete the cached stat info for a file path.
1534 * The cache key is salted for a while to prevent race conditions.
1536 * @param $path string Storage path
1538 final protected function deleteFileCache( $path ) {
1539 if ( !$this->memCache
->set( $this->fileCacheKey( $path ), 'PURGED', 300 ) ) {
1540 trigger_error( "Unable to delete stat cache for file $path." );
1545 * Do a batch lookup from cache for file stats for all paths
1546 * used in a list of storage paths or FileOp objects.
1548 * @param $items Array List of storage paths or FileOps
1551 final protected function primeFileCache( array $items ) {
1552 wfProfileIn( __METHOD__
);
1553 wfProfileIn( __METHOD__
. '-' . $this->name
);
1555 $paths = array(); // list of storage paths
1556 $pathNames = array(); // (cache key => storage path)
1557 // Get all the paths/containers from the items...
1558 foreach ( $items as $item ) {
1559 if ( $item instanceof FileOp
) {
1560 $paths = array_merge( $paths, $item->storagePathsRead() );
1561 $paths = array_merge( $paths, $item->storagePathsChanged() );
1562 } elseif ( self
::isStoragePath( $item ) ) {
1566 // Get all the corresponding cache keys for paths...
1567 foreach ( $paths as $path ) {
1568 list( $cont, $rel, $s ) = $this->resolveStoragePath( $path );
1569 if ( $rel !== null ) { // valid path for this backend
1570 $pathNames[$this->fileCacheKey( $path )] = $path;
1573 // Get all cache entries for these container cache keys...
1574 $values = $this->memCache
->getMulti( array_keys( $pathNames ) );
1575 foreach ( $values as $cacheKey => $val ) {
1576 if ( is_array( $val ) ) {
1577 $path = $pathNames[$cacheKey];
1578 $this->cheapCache
->set( $path, 'stat', $val );
1579 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1580 $this->cheapCache
->set( $path, 'sha1',
1581 array( 'hash' => $val['sha1'], 'latest' => $val['latest'] ) );
1586 wfProfileOut( __METHOD__
. '-' . $this->name
);
1587 wfProfileOut( __METHOD__
);
1591 * Set the 'concurrency' option from a list of operation options
1593 * @param $opts array Map of operation options
1596 final protected function setConcurrencyFlags( array $opts ) {
1597 $opts['concurrency'] = 1; // off
1598 if ( $this->parallelize
=== 'implicit' ) {
1599 if ( !isset( $opts['parallelize'] ) ||
$opts['parallelize'] ) {
1600 $opts['concurrency'] = $this->concurrency
;
1602 } elseif ( $this->parallelize
=== 'explicit' ) {
1603 if ( !empty( $opts['parallelize'] ) ) {
1604 $opts['concurrency'] = $this->concurrency
;
1612 * FileBackendStore helper class for performing asynchronous file operations.
1614 * For example, calling FileBackendStore::createInternal() with the "async"
1615 * param flag may result in a Status that contains this object as a value.
1616 * This class is largely backend-specific and is mostly just "magic" to be
1617 * passed to FileBackendStore::executeOpHandlesInternal().
1619 abstract class FileBackendStoreOpHandle
{
1621 public $params = array(); // params to caller functions
1622 /** @var FileBackendStore */
1625 public $resourcesToClose = array();
1627 public $call; // string; name that identifies the function called
1630 * Close all open file handles
1634 public function closeResources() {
1635 array_map( 'fclose', $this->resourcesToClose
);
1640 * FileBackendStore helper function to handle listings that span container shards.
1641 * Do not use this class from places outside of FileBackendStore.
1643 * @ingroup FileBackend
1645 abstract class FileBackendStoreShardListIterator
implements Iterator
{
1646 /** @var FileBackendStore */
1651 protected $shardSuffixes;
1652 protected $container; // string; full container name
1653 protected $directory; // string; resolved relative path
1655 /** @var Traversable */
1657 protected $curShard = 0; // integer
1658 protected $pos = 0; // integer
1661 protected $multiShardPaths = array(); // (rel path => 1)
1664 * @param $backend FileBackendStore
1665 * @param $container string Full storage container name
1666 * @param $dir string Storage directory relative to container
1667 * @param $suffixes Array List of container shard suffixes
1668 * @param $params Array
1670 public function __construct(
1671 FileBackendStore
$backend, $container, $dir, array $suffixes, array $params
1673 $this->backend
= $backend;
1674 $this->container
= $container;
1675 $this->directory
= $dir;
1676 $this->shardSuffixes
= $suffixes;
1677 $this->params
= $params;
1681 * @see Iterator::key()
1684 public function key() {
1689 * @see Iterator::valid()
1692 public function valid() {
1693 if ( $this->iter
instanceof Iterator
) {
1694 return $this->iter
->valid();
1695 } elseif ( is_array( $this->iter
) ) {
1696 return ( current( $this->iter
) !== false ); // no paths can have this value
1698 return false; // some failure?
1702 * @see Iterator::current()
1703 * @return string|bool String or false
1705 public function current() {
1706 return ( $this->iter
instanceof Iterator
)
1707 ?
$this->iter
->current()
1708 : current( $this->iter
);
1712 * @see Iterator::next()
1715 public function next() {
1717 ( $this->iter
instanceof Iterator
) ?
$this->iter
->next() : next( $this->iter
);
1719 $continue = false; // keep scanning shards?
1720 $this->filterViaNext(); // filter out duplicates
1721 // Find the next non-empty shard if no elements are left
1722 if ( !$this->valid() ) {
1723 $this->nextShardIteratorIfNotValid();
1724 $continue = $this->valid(); // re-filter unless we ran out of shards
1726 } while ( $continue );
1730 * @see Iterator::rewind()
1733 public function rewind() {
1735 $this->curShard
= 0;
1736 $this->setIteratorFromCurrentShard();
1738 $continue = false; // keep scanning shards?
1739 $this->filterViaNext(); // filter out duplicates
1740 // Find the next non-empty shard if no elements are left
1741 if ( !$this->valid() ) {
1742 $this->nextShardIteratorIfNotValid();
1743 $continue = $this->valid(); // re-filter unless we ran out of shards
1745 } while ( $continue );
1749 * Filter out duplicate items by advancing to the next ones
1751 protected function filterViaNext() {
1752 while ( $this->valid() ) {
1753 $rel = $this->iter
->current(); // path relative to given directory
1754 $path = $this->params
['dir'] . "/{$rel}"; // full storage path
1755 if ( $this->backend
->isSingleShardPathInternal( $path ) ) {
1756 break; // path is only on one shard; no issue with duplicates
1757 } elseif ( isset( $this->multiShardPaths
[$rel] ) ) {
1758 // Don't keep listing paths that are on multiple shards
1759 ( $this->iter
instanceof Iterator
) ?
$this->iter
->next() : next( $this->iter
);
1761 $this->multiShardPaths
[$rel] = 1;
1768 * If the list iterator for this container shard is out of items,
1769 * then move on to the next container that has items.
1770 * If there are none, then it advances to the last container.
1772 protected function nextShardIteratorIfNotValid() {
1773 while ( !$this->valid() && ++
$this->curShard
< count( $this->shardSuffixes
) ) {
1774 $this->setIteratorFromCurrentShard();
1779 * Set the list iterator to that of the current container shard
1781 protected function setIteratorFromCurrentShard() {
1782 $this->iter
= $this->listFromShard(
1783 $this->container
. $this->shardSuffixes
[$this->curShard
],
1784 $this->directory
, $this->params
);
1785 // Start loading results so that current() works
1786 if ( $this->iter
) {
1787 ( $this->iter
instanceof Iterator
) ?
$this->iter
->rewind() : reset( $this->iter
);
1792 * Get the list for a given container shard
1794 * @param $container string Resolved container name
1795 * @param $dir string Resolved path relative to container
1796 * @param $params Array
1797 * @return Traversable|Array|null
1799 abstract protected function listFromShard( $container, $dir, array $params );
1803 * Iterator for listing directories
1805 class FileBackendStoreShardDirIterator
extends FileBackendStoreShardListIterator
{
1807 * @see FileBackendStoreShardListIterator::listFromShard()
1808 * @return Array|null|Traversable
1810 protected function listFromShard( $container, $dir, array $params ) {
1811 return $this->backend
->getDirectoryListInternal( $container, $dir, $params );
1816 * Iterator for listing regular files
1818 class FileBackendStoreShardFileIterator
extends FileBackendStoreShardListIterator
{
1820 * @see FileBackendStoreShardListIterator::listFromShard()
1821 * @return Array|null|Traversable
1823 protected function listFromShard( $container, $dir, array $params ) {
1824 return $this->backend
->getFileListInternal( $container, $dir, $params );