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 * - async : Status will be returned immediately if supported.
93 * If the status is OK, then its value field will be
94 * set to a FileBackendStoreOpHandle object.
96 * @param $params Array
99 final public function createInternal( array $params ) {
100 wfProfileIn( __METHOD__
);
101 wfProfileIn( __METHOD__
. '-' . $this->name
);
102 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
103 $status = Status
::newFatal( 'backend-fail-maxsize',
104 $params['dst'], $this->maxFileSizeInternal() );
106 $status = $this->doCreateInternal( $params );
107 $this->clearCache( array( $params['dst'] ) );
108 $this->deleteFileCache( $params['dst'] ); // persistent cache
110 wfProfileOut( __METHOD__
. '-' . $this->name
);
111 wfProfileOut( __METHOD__
);
116 * @see FileBackendStore::createInternal()
118 abstract protected function doCreateInternal( array $params );
121 * Store a file into the backend from a file on disk.
122 * Do not call this function from places outside FileBackend and FileOp.
125 * - src : source path on disk
126 * - dst : destination storage path
127 * - overwrite : overwrite any file that exists at the destination
128 * - async : Status will be returned immediately if supported.
129 * If the status is OK, then its value field will be
130 * set to a FileBackendStoreOpHandle object.
132 * @param $params Array
135 final public function storeInternal( array $params ) {
136 wfProfileIn( __METHOD__
);
137 wfProfileIn( __METHOD__
. '-' . $this->name
);
138 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
139 $status = Status
::newFatal( 'backend-fail-maxsize',
140 $params['dst'], $this->maxFileSizeInternal() );
142 $status = $this->doStoreInternal( $params );
143 $this->clearCache( array( $params['dst'] ) );
144 $this->deleteFileCache( $params['dst'] ); // persistent cache
146 wfProfileOut( __METHOD__
. '-' . $this->name
);
147 wfProfileOut( __METHOD__
);
152 * @see FileBackendStore::storeInternal()
154 abstract protected function doStoreInternal( array $params );
157 * Copy a file from one storage path to another in the backend.
158 * Do not call this function from places outside FileBackend and FileOp.
161 * - src : source storage path
162 * - dst : destination storage path
163 * - overwrite : overwrite any file that exists at the destination
164 * - async : Status will be returned immediately if supported.
165 * If the status is OK, then its value field will be
166 * set to a FileBackendStoreOpHandle object.
168 * @param $params Array
171 final public function copyInternal( array $params ) {
172 wfProfileIn( __METHOD__
);
173 wfProfileIn( __METHOD__
. '-' . $this->name
);
174 $status = $this->doCopyInternal( $params );
175 $this->clearCache( array( $params['dst'] ) );
176 $this->deleteFileCache( $params['dst'] ); // persistent cache
177 wfProfileOut( __METHOD__
. '-' . $this->name
);
178 wfProfileOut( __METHOD__
);
183 * @see FileBackendStore::copyInternal()
185 abstract protected function doCopyInternal( array $params );
188 * Delete a file at the storage path.
189 * Do not call this function from places outside FileBackend and FileOp.
192 * - src : source storage path
193 * - ignoreMissingSource : do nothing if the source file does not exist
194 * - async : Status will be returned immediately if supported.
195 * If the status is OK, then its value field will be
196 * set to a FileBackendStoreOpHandle object.
198 * @param $params Array
201 final public function deleteInternal( array $params ) {
202 wfProfileIn( __METHOD__
);
203 wfProfileIn( __METHOD__
. '-' . $this->name
);
204 $status = $this->doDeleteInternal( $params );
205 $this->clearCache( array( $params['src'] ) );
206 $this->deleteFileCache( $params['src'] ); // persistent cache
207 wfProfileOut( __METHOD__
. '-' . $this->name
);
208 wfProfileOut( __METHOD__
);
213 * @see FileBackendStore::deleteInternal()
215 abstract protected function doDeleteInternal( array $params );
218 * Move a file from one storage path to another in the backend.
219 * Do not call this function from places outside FileBackend and FileOp.
222 * - src : source storage path
223 * - dst : destination storage path
224 * - overwrite : overwrite any file that exists at the destination
225 * - async : Status will be returned immediately if supported.
226 * If the status is OK, then its value field will be
227 * set to a FileBackendStoreOpHandle object.
229 * @param $params Array
232 final public function moveInternal( array $params ) {
233 wfProfileIn( __METHOD__
);
234 wfProfileIn( __METHOD__
. '-' . $this->name
);
235 $status = $this->doMoveInternal( $params );
236 $this->clearCache( array( $params['src'], $params['dst'] ) );
237 $this->deleteFileCache( $params['src'] ); // persistent cache
238 $this->deleteFileCache( $params['dst'] ); // persistent cache
239 wfProfileOut( __METHOD__
. '-' . $this->name
);
240 wfProfileOut( __METHOD__
);
245 * @see FileBackendStore::moveInternal()
248 protected function doMoveInternal( array $params ) {
249 unset( $params['async'] ); // two steps, won't work here :)
250 // Copy source to dest
251 $status = $this->copyInternal( $params );
252 if ( $status->isOK() ) {
253 // Delete source (only fails due to races or medium going down)
254 $status->merge( $this->deleteInternal( array( 'src' => $params['src'] ) ) );
255 $status->setResult( true, $status->value
); // ignore delete() errors
261 * No-op file operation that does nothing.
262 * Do not call this function from places outside FileBackend and FileOp.
264 * @param $params Array
267 final public function nullInternal( array $params ) {
268 return Status
::newGood();
272 * @see FileBackend::concatenate()
275 final public function concatenate( array $params ) {
276 wfProfileIn( __METHOD__
);
277 wfProfileIn( __METHOD__
. '-' . $this->name
);
278 $status = Status
::newGood();
280 // Try to lock the source files for the scope of this function
281 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager
::LOCK_UW
, $status );
282 if ( $status->isOK() ) {
283 // Actually do the concatenation
284 $status->merge( $this->doConcatenate( $params ) );
287 wfProfileOut( __METHOD__
. '-' . $this->name
);
288 wfProfileOut( __METHOD__
);
293 * @see FileBackendStore::concatenate()
296 protected function doConcatenate( array $params ) {
297 $status = Status
::newGood();
298 $tmpPath = $params['dst']; // convenience
300 // Check that the specified temp file is valid...
301 wfSuppressWarnings();
302 $ok = ( is_file( $tmpPath ) && !filesize( $tmpPath ) );
304 if ( !$ok ) { // not present or not empty
305 $status->fatal( 'backend-fail-opentemp', $tmpPath );
309 // Build up the temp file using the source chunks (in order)...
310 $tmpHandle = fopen( $tmpPath, 'ab' );
311 if ( $tmpHandle === false ) {
312 $status->fatal( 'backend-fail-opentemp', $tmpPath );
315 foreach ( $params['srcs'] as $virtualSource ) {
316 // Get a local FS version of the chunk
317 $tmpFile = $this->getLocalReference( array( 'src' => $virtualSource ) );
319 $status->fatal( 'backend-fail-read', $virtualSource );
322 // Get a handle to the local FS version
323 $sourceHandle = fopen( $tmpFile->getPath(), 'r' );
324 if ( $sourceHandle === false ) {
325 fclose( $tmpHandle );
326 $status->fatal( 'backend-fail-read', $virtualSource );
329 // Append chunk to file (pass chunk size to avoid magic quotes)
330 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
331 fclose( $sourceHandle );
332 fclose( $tmpHandle );
333 $status->fatal( 'backend-fail-writetemp', $tmpPath );
336 fclose( $sourceHandle );
338 if ( !fclose( $tmpHandle ) ) {
339 $status->fatal( 'backend-fail-closetemp', $tmpPath );
343 clearstatcache(); // temp file changed
349 * @see FileBackend::doPrepare()
352 final protected function doPrepare( array $params ) {
353 wfProfileIn( __METHOD__
);
354 wfProfileIn( __METHOD__
. '-' . $this->name
);
356 $status = Status
::newGood();
357 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
358 if ( $dir === null ) {
359 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
360 wfProfileOut( __METHOD__
. '-' . $this->name
);
361 wfProfileOut( __METHOD__
);
362 return $status; // invalid storage path
365 if ( $shard !== null ) { // confined to a single container/shard
366 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
367 } else { // directory is on several shards
368 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
369 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
370 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
371 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
375 wfProfileOut( __METHOD__
. '-' . $this->name
);
376 wfProfileOut( __METHOD__
);
381 * @see FileBackendStore::doPrepare()
384 protected function doPrepareInternal( $container, $dir, array $params ) {
385 return Status
::newGood();
389 * @see FileBackend::doSecure()
392 final protected function doSecure( array $params ) {
393 wfProfileIn( __METHOD__
);
394 wfProfileIn( __METHOD__
. '-' . $this->name
);
395 $status = Status
::newGood();
397 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
398 if ( $dir === null ) {
399 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
400 wfProfileOut( __METHOD__
. '-' . $this->name
);
401 wfProfileOut( __METHOD__
);
402 return $status; // invalid storage path
405 if ( $shard !== null ) { // confined to a single container/shard
406 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
407 } else { // directory is on several shards
408 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
409 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
410 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
411 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
415 wfProfileOut( __METHOD__
. '-' . $this->name
);
416 wfProfileOut( __METHOD__
);
421 * @see FileBackendStore::doSecure()
424 protected function doSecureInternal( $container, $dir, array $params ) {
425 return Status
::newGood();
429 * @see FileBackend::doPublish()
432 final protected function doPublish( array $params ) {
433 wfProfileIn( __METHOD__
);
434 wfProfileIn( __METHOD__
. '-' . $this->name
);
435 $status = Status
::newGood();
437 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
438 if ( $dir === null ) {
439 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
440 wfProfileOut( __METHOD__
. '-' . $this->name
);
441 wfProfileOut( __METHOD__
);
442 return $status; // invalid storage path
445 if ( $shard !== null ) { // confined to a single container/shard
446 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
447 } else { // directory is on several shards
448 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
449 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
450 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
451 $status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
455 wfProfileOut( __METHOD__
. '-' . $this->name
);
456 wfProfileOut( __METHOD__
);
461 * @see FileBackendStore::doPublish()
464 protected function doPublishInternal( $container, $dir, array $params ) {
465 return Status
::newGood();
469 * @see FileBackend::doClean()
472 final protected function doClean( array $params ) {
473 wfProfileIn( __METHOD__
);
474 wfProfileIn( __METHOD__
. '-' . $this->name
);
475 $status = Status
::newGood();
477 // Recursive: first delete all empty subdirs recursively
478 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
479 $subDirsRel = $this->getTopDirectoryList( array( 'dir' => $params['dir'] ) );
480 if ( $subDirsRel !== null ) { // no errors
481 foreach ( $subDirsRel as $subDirRel ) {
482 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
483 $status->merge( $this->doClean( array( 'dir' => $subDir ) +
$params ) );
488 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
489 if ( $dir === null ) {
490 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
491 wfProfileOut( __METHOD__
. '-' . $this->name
);
492 wfProfileOut( __METHOD__
);
493 return $status; // invalid storage path
496 // Attempt to lock this directory...
497 $filesLockEx = array( $params['dir'] );
498 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
499 if ( !$status->isOK() ) {
500 wfProfileOut( __METHOD__
. '-' . $this->name
);
501 wfProfileOut( __METHOD__
);
502 return $status; // abort
505 if ( $shard !== null ) { // confined to a single container/shard
506 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
507 $this->deleteContainerCache( $fullCont ); // purge cache
508 } else { // directory is on several shards
509 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
510 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
511 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
512 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
513 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
517 wfProfileOut( __METHOD__
. '-' . $this->name
);
518 wfProfileOut( __METHOD__
);
523 * @see FileBackendStore::doClean()
526 protected function doCleanInternal( $container, $dir, array $params ) {
527 return Status
::newGood();
531 * @see FileBackend::fileExists()
534 final public function fileExists( array $params ) {
535 wfProfileIn( __METHOD__
);
536 wfProfileIn( __METHOD__
. '-' . $this->name
);
537 $stat = $this->getFileStat( $params );
538 wfProfileOut( __METHOD__
. '-' . $this->name
);
539 wfProfileOut( __METHOD__
);
540 return ( $stat === null ) ?
null : (bool)$stat; // null => failure
544 * @see FileBackend::getFileTimestamp()
547 final public function getFileTimestamp( array $params ) {
548 wfProfileIn( __METHOD__
);
549 wfProfileIn( __METHOD__
. '-' . $this->name
);
550 $stat = $this->getFileStat( $params );
551 wfProfileOut( __METHOD__
. '-' . $this->name
);
552 wfProfileOut( __METHOD__
);
553 return $stat ?
$stat['mtime'] : false;
557 * @see FileBackend::getFileSize()
560 final public function getFileSize( array $params ) {
561 wfProfileIn( __METHOD__
);
562 wfProfileIn( __METHOD__
. '-' . $this->name
);
563 $stat = $this->getFileStat( $params );
564 wfProfileOut( __METHOD__
. '-' . $this->name
);
565 wfProfileOut( __METHOD__
);
566 return $stat ?
$stat['size'] : false;
570 * @see FileBackend::getFileStat()
573 final public function getFileStat( array $params ) {
574 $path = self
::normalizeStoragePath( $params['src'] );
575 if ( $path === null ) {
576 return false; // invalid storage path
578 wfProfileIn( __METHOD__
);
579 wfProfileIn( __METHOD__
. '-' . $this->name
);
580 $latest = !empty( $params['latest'] ); // use latest data?
581 if ( !$this->cheapCache
->has( $path, 'stat' ) ) {
582 $this->primeFileCache( array( $path ) ); // check persistent cache
584 if ( $this->cheapCache
->has( $path, 'stat' ) ) {
585 $stat = $this->cheapCache
->get( $path, 'stat' );
586 // If we want the latest data, check that this cached
587 // value was in fact fetched with the latest available data.
588 if ( !$latest ||
$stat['latest'] ) {
589 wfProfileOut( __METHOD__
. '-' . $this->name
);
590 wfProfileOut( __METHOD__
);
594 wfProfileIn( __METHOD__
. '-miss' );
595 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
596 $stat = $this->doGetFileStat( $params );
597 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
598 wfProfileOut( __METHOD__
. '-miss' );
599 if ( is_array( $stat ) ) { // don't cache negatives
600 $stat['latest'] = $latest;
601 $this->cheapCache
->set( $path, 'stat', $stat );
602 $this->setFileCache( $path, $stat ); // update persistent cache
603 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
604 $this->cheapCache
->set( $path, 'sha1',
605 array( 'hash' => $stat['sha1'], 'latest' => $latest ) );
608 wfDebug( __METHOD__
. ": File $path does not exist.\n" );
610 wfProfileOut( __METHOD__
. '-' . $this->name
);
611 wfProfileOut( __METHOD__
);
616 * @see FileBackendStore::getFileStat()
618 abstract protected function doGetFileStat( array $params );
621 * @see FileBackend::getFileContents()
622 * @return bool|string
624 public function getFileContents( array $params ) {
625 wfProfileIn( __METHOD__
);
626 wfProfileIn( __METHOD__
. '-' . $this->name
);
627 $tmpFile = $this->getLocalReference( $params );
629 wfProfileOut( __METHOD__
. '-' . $this->name
);
630 wfProfileOut( __METHOD__
);
633 wfSuppressWarnings();
634 $data = file_get_contents( $tmpFile->getPath() );
636 wfProfileOut( __METHOD__
. '-' . $this->name
);
637 wfProfileOut( __METHOD__
);
642 * @see FileBackend::getFileSha1Base36()
643 * @return bool|string
645 final public function getFileSha1Base36( array $params ) {
646 $path = self
::normalizeStoragePath( $params['src'] );
647 if ( $path === null ) {
648 return false; // invalid storage path
650 wfProfileIn( __METHOD__
);
651 wfProfileIn( __METHOD__
. '-' . $this->name
);
652 $latest = !empty( $params['latest'] ); // use latest data?
653 if ( $this->cheapCache
->has( $path, 'sha1' ) ) {
654 $stat = $this->cheapCache
->get( $path, 'sha1' );
655 // If we want the latest data, check that this cached
656 // value was in fact fetched with the latest available data.
657 if ( !$latest ||
$stat['latest'] ) {
658 wfProfileOut( __METHOD__
. '-' . $this->name
);
659 wfProfileOut( __METHOD__
);
660 return $stat['hash'];
663 wfProfileIn( __METHOD__
. '-miss' );
664 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
665 $hash = $this->doGetFileSha1Base36( $params );
666 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
667 wfProfileOut( __METHOD__
. '-miss' );
668 if ( $hash ) { // don't cache negatives
669 $this->cheapCache
->set( $path, 'sha1',
670 array( 'hash' => $hash, 'latest' => $latest ) );
672 wfProfileOut( __METHOD__
. '-' . $this->name
);
673 wfProfileOut( __METHOD__
);
678 * @see FileBackendStore::getFileSha1Base36()
679 * @return bool|string
681 protected function doGetFileSha1Base36( array $params ) {
682 $fsFile = $this->getLocalReference( $params );
686 return $fsFile->getSha1Base36();
691 * @see FileBackend::getFileProps()
694 final public function getFileProps( array $params ) {
695 wfProfileIn( __METHOD__
);
696 wfProfileIn( __METHOD__
. '-' . $this->name
);
697 $fsFile = $this->getLocalReference( $params );
698 $props = $fsFile ?
$fsFile->getProps() : FSFile
::placeholderProps();
699 wfProfileOut( __METHOD__
. '-' . $this->name
);
700 wfProfileOut( __METHOD__
);
705 * @see FileBackend::getLocalReference()
706 * @return TempFSFile|null
708 public function getLocalReference( array $params ) {
709 $path = self
::normalizeStoragePath( $params['src'] );
710 if ( $path === null ) {
711 return null; // invalid storage path
713 wfProfileIn( __METHOD__
);
714 wfProfileIn( __METHOD__
. '-' . $this->name
);
715 $latest = !empty( $params['latest'] ); // use latest data?
716 if ( $this->expensiveCache
->has( $path, 'localRef' ) ) {
717 $val = $this->expensiveCache
->get( $path, 'localRef' );
718 // If we want the latest data, check that this cached
719 // value was in fact fetched with the latest available data.
720 if ( !$latest ||
$val['latest'] ) {
721 wfProfileOut( __METHOD__
. '-' . $this->name
);
722 wfProfileOut( __METHOD__
);
723 return $val['object'];
726 $tmpFile = $this->getLocalCopy( $params );
727 if ( $tmpFile ) { // don't cache negatives
728 $this->expensiveCache
->set( $path, 'localRef',
729 array( 'object' => $tmpFile, 'latest' => $latest ) );
731 wfProfileOut( __METHOD__
. '-' . $this->name
);
732 wfProfileOut( __METHOD__
);
737 * @see FileBackend::streamFile()
740 final public function streamFile( array $params ) {
741 wfProfileIn( __METHOD__
);
742 wfProfileIn( __METHOD__
. '-' . $this->name
);
743 $status = Status
::newGood();
745 $info = $this->getFileStat( $params );
746 if ( !$info ) { // let StreamFile handle the 404
747 $status->fatal( 'backend-fail-notexists', $params['src'] );
750 // Set output buffer and HTTP headers for stream
751 $extraHeaders = isset( $params['headers'] ) ?
$params['headers'] : array();
752 $res = StreamFile
::prepareForStream( $params['src'], $info, $extraHeaders );
753 if ( $res == StreamFile
::NOT_MODIFIED
) {
754 // do nothing; client cache is up to date
755 } elseif ( $res == StreamFile
::READY_STREAM
) {
756 wfProfileIn( __METHOD__
. '-send' );
757 wfProfileIn( __METHOD__
. '-send-' . $this->name
);
758 $status = $this->doStreamFile( $params );
759 wfProfileOut( __METHOD__
. '-send-' . $this->name
);
760 wfProfileOut( __METHOD__
. '-send' );
762 $status->fatal( 'backend-fail-stream', $params['src'] );
765 wfProfileOut( __METHOD__
. '-' . $this->name
);
766 wfProfileOut( __METHOD__
);
771 * @see FileBackendStore::streamFile()
774 protected function doStreamFile( array $params ) {
775 $status = Status
::newGood();
777 $fsFile = $this->getLocalReference( $params );
779 $status->fatal( 'backend-fail-stream', $params['src'] );
780 } elseif ( !readfile( $fsFile->getPath() ) ) {
781 $status->fatal( 'backend-fail-stream', $params['src'] );
788 * @see FileBackend::directoryExists()
791 final public function directoryExists( array $params ) {
792 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
793 if ( $dir === null ) {
794 return false; // invalid storage path
796 if ( $shard !== null ) { // confined to a single container/shard
797 return $this->doDirectoryExists( $fullCont, $dir, $params );
798 } else { // directory is on several shards
799 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
800 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
801 $res = false; // response
802 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
803 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
807 } elseif ( $exists === null ) { // error?
808 $res = null; // if we don't find anything, it is indeterminate
816 * @see FileBackendStore::directoryExists()
818 * @param $container string Resolved container name
819 * @param $dir string Resolved path relative to container
820 * @param $params Array
823 abstract protected function doDirectoryExists( $container, $dir, array $params );
826 * @see FileBackend::getDirectoryList()
827 * @return Traversable|Array|null Returns null on failure
829 final public function getDirectoryList( array $params ) {
830 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
831 if ( $dir === null ) { // invalid storage path
834 if ( $shard !== null ) {
835 // File listing is confined to a single container/shard
836 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
838 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
839 // File listing spans multiple containers/shards
840 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
841 return new FileBackendStoreShardDirIterator( $this,
842 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
847 * Do not call this function from places outside FileBackend
849 * @see FileBackendStore::getDirectoryList()
851 * @param $container string Resolved container name
852 * @param $dir string Resolved path relative to container
853 * @param $params Array
854 * @return Traversable|Array|null Returns null on failure
856 abstract public function getDirectoryListInternal( $container, $dir, array $params );
859 * @see FileBackend::getFileList()
860 * @return Traversable|Array|null Returns null on failure
862 final public function getFileList( array $params ) {
863 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
864 if ( $dir === null ) { // invalid storage path
867 if ( $shard !== null ) {
868 // File listing is confined to a single container/shard
869 return $this->getFileListInternal( $fullCont, $dir, $params );
871 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
872 // File listing spans multiple containers/shards
873 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
874 return new FileBackendStoreShardFileIterator( $this,
875 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
880 * Do not call this function from places outside FileBackend
882 * @see FileBackendStore::getFileList()
884 * @param $container string Resolved container name
885 * @param $dir string Resolved path relative to container
886 * @param $params Array
887 * @return Traversable|Array|null Returns null on failure
889 abstract public function getFileListInternal( $container, $dir, array $params );
892 * Return a list of FileOp objects from a list of operations.
893 * Do not call this function from places outside FileBackend.
895 * The result must have the same number of items as the input.
896 * An exception is thrown if an unsupported operation is requested.
898 * @param $ops Array Same format as doOperations()
899 * @return Array List of FileOp objects
900 * @throws MWException
902 final public function getOperationsInternal( array $ops ) {
903 $supportedOps = array(
904 'store' => 'StoreFileOp',
905 'copy' => 'CopyFileOp',
906 'move' => 'MoveFileOp',
907 'delete' => 'DeleteFileOp',
908 'create' => 'CreateFileOp',
909 'null' => 'NullFileOp'
912 $performOps = array(); // array of FileOp objects
913 // Build up ordered array of FileOps...
914 foreach ( $ops as $operation ) {
915 $opName = $operation['op'];
916 if ( isset( $supportedOps[$opName] ) ) {
917 $class = $supportedOps[$opName];
918 // Get params for this operation
919 $params = $operation;
920 // Append the FileOp class
921 $performOps[] = new $class( $this, $params );
923 throw new MWException( "Operation '$opName' is not supported." );
931 * Get a list of storage paths to lock for a list of operations
932 * Returns an array with 'sh' (shared) and 'ex' (exclusive) keys,
933 * each corresponding to a list of storage paths to be locked.
935 * @param $performOps Array List of FileOp objects
936 * @return Array ('sh' => list of paths, 'ex' => list of paths)
938 final public function getPathsToLockForOpsInternal( array $performOps ) {
939 // Build up a list of files to lock...
940 $paths = array( 'sh' => array(), 'ex' => array() );
941 foreach ( $performOps as $fileOp ) {
942 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
943 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
945 // Optimization: if doing an EX lock anyway, don't also set an SH one
946 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
947 // Get a shared lock on the parent directory of each path changed
948 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
954 * @see FileBackend::getScopedLocksForOps()
957 public function getScopedLocksForOps( array $ops, Status
$status ) {
958 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
960 $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status ),
961 $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status )
966 * @see FileBackend::doOperationsInternal()
969 final protected function doOperationsInternal( array $ops, array $opts ) {
970 wfProfileIn( __METHOD__
);
971 wfProfileIn( __METHOD__
. '-' . $this->name
);
972 $status = Status
::newGood();
974 // Build up a list of FileOps...
975 $performOps = $this->getOperationsInternal( $ops );
977 // Acquire any locks as needed...
978 if ( empty( $opts['nonLocking'] ) ) {
979 // Build up a list of files to lock...
980 $paths = $this->getPathsToLockForOpsInternal( $performOps );
981 // Try to lock those files for the scope of this function...
982 $scopeLockS = $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status );
983 $scopeLockE = $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status );
984 if ( !$status->isOK() ) {
985 wfProfileOut( __METHOD__
. '-' . $this->name
);
986 wfProfileOut( __METHOD__
);
987 return $status; // abort
991 // Clear any file cache entries (after locks acquired)
992 if ( empty( $opts['preserveCache'] ) ) {
996 // Load from the persistent file and container caches
997 $this->primeFileCache( $performOps );
998 $this->primeContainerCache( $performOps );
1000 // Actually attempt the operation batch...
1001 $subStatus = FileOpBatch
::attempt( $performOps, $opts, $this->fileJournal
);
1003 // Merge errors into status fields
1004 $status->merge( $subStatus );
1005 $status->success
= $subStatus->success
; // not done in merge()
1007 wfProfileOut( __METHOD__
. '-' . $this->name
);
1008 wfProfileOut( __METHOD__
);
1013 * @see FileBackend::doQuickOperationsInternal()
1015 * @throws MWException
1017 final protected function doQuickOperationsInternal( array $ops ) {
1018 wfProfileIn( __METHOD__
);
1019 wfProfileIn( __METHOD__
. '-' . $this->name
);
1020 $status = Status
::newGood();
1022 $supportedOps = array( 'create', 'store', 'copy', 'move', 'delete', 'null' );
1023 $async = ( $this->parallelize
=== 'implicit' );
1024 $maxConcurrency = $this->concurrency
; // throttle
1026 $statuses = array(); // array of (index => Status)
1027 $fileOpHandles = array(); // list of (index => handle) arrays
1028 $curFileOpHandles = array(); // current handle batch
1029 // Perform the sync-only ops and build up op handles for the async ops...
1030 foreach ( $ops as $index => $params ) {
1031 if ( !in_array( $params['op'], $supportedOps ) ) {
1032 wfProfileOut( __METHOD__
. '-' . $this->name
);
1033 wfProfileOut( __METHOD__
);
1034 throw new MWException( "Operation '{$params['op']}' is not supported." );
1036 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1037 $subStatus = $this->$method( array( 'async' => $async ) +
$params );
1038 if ( $subStatus->value
instanceof FileBackendStoreOpHandle
) { // async
1039 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1040 $fileOpHandles[] = $curFileOpHandles; // push this batch
1041 $curFileOpHandles = array();
1043 $curFileOpHandles[$index] = $subStatus->value
; // keep index
1044 } else { // error or completed
1045 $statuses[$index] = $subStatus; // keep index
1048 if ( count( $curFileOpHandles ) ) {
1049 $fileOpHandles[] = $curFileOpHandles; // last batch
1051 // Do all the async ops that can be done concurrently...
1052 foreach ( $fileOpHandles as $fileHandleBatch ) {
1053 $statuses = $statuses +
$this->executeOpHandlesInternal( $fileHandleBatch );
1055 // Marshall and merge all the responses...
1056 foreach ( $statuses as $index => $subStatus ) {
1057 $status->merge( $subStatus );
1058 if ( $subStatus->isOK() ) {
1059 $status->success
[$index] = true;
1060 ++
$status->successCount
;
1062 $status->success
[$index] = false;
1063 ++
$status->failCount
;
1067 wfProfileOut( __METHOD__
. '-' . $this->name
);
1068 wfProfileOut( __METHOD__
);
1073 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1074 * The resulting Status object fields will correspond
1075 * to the order in which the handles where given.
1077 * @param $handles Array List of FileBackendStoreOpHandle objects
1078 * @return Array Map of Status objects
1079 * @throws MWException
1081 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1082 wfProfileIn( __METHOD__
);
1083 wfProfileIn( __METHOD__
. '-' . $this->name
);
1084 foreach ( $fileOpHandles as $fileOpHandle ) {
1085 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle
) ) {
1086 throw new MWException( "Given a non-FileBackendStoreOpHandle object." );
1087 } elseif ( $fileOpHandle->backend
->getName() !== $this->getName() ) {
1088 throw new MWException( "Given a FileBackendStoreOpHandle for the wrong backend." );
1091 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1092 foreach ( $fileOpHandles as $fileOpHandle ) {
1093 $fileOpHandle->closeResources();
1095 wfProfileOut( __METHOD__
. '-' . $this->name
);
1096 wfProfileOut( __METHOD__
);
1101 * @see FileBackendStore::executeOpHandlesInternal()
1102 * @return Array List of corresponding Status objects
1104 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1105 foreach ( $fileOpHandles as $fileOpHandle ) { // OK if empty
1106 throw new MWException( "This backend supports no asynchronous operations." );
1112 * @see FileBackend::preloadCache()
1114 final public function preloadCache( array $paths ) {
1115 $fullConts = array(); // full container names
1116 foreach ( $paths as $path ) {
1117 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1118 $fullConts[] = $fullCont;
1120 // Load from the persistent file and container caches
1121 $this->primeContainerCache( $fullConts );
1122 $this->primeFileCache( $paths );
1126 * @see FileBackend::clearCache()
1128 final public function clearCache( array $paths = null ) {
1129 if ( is_array( $paths ) ) {
1130 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1131 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1133 if ( $paths === null ) {
1134 $this->cheapCache
->clear();
1135 $this->expensiveCache
->clear();
1137 foreach ( $paths as $path ) {
1138 $this->cheapCache
->clear( $path );
1139 $this->expensiveCache
->clear( $path );
1142 $this->doClearCache( $paths );
1146 * Clears any additional stat caches for storage paths
1148 * @see FileBackend::clearCache()
1150 * @param $paths Array Storage paths (optional)
1153 protected function doClearCache( array $paths = null ) {}
1156 * Is this a key/value store where directories are just virtual?
1157 * Virtual directories exists in so much as files exists that are
1158 * prefixed with the directory path followed by a forward slash.
1162 abstract protected function directoriesAreVirtual();
1165 * Check if a container name is valid.
1166 * This checks for for length and illegal characters.
1168 * @param $container string
1171 final protected static function isValidContainerName( $container ) {
1172 // This accounts for Swift and S3 restrictions while leaving room
1173 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1174 // This disallows directory separators or traversal characters.
1175 // Note that matching strings URL encode to the same string;
1176 // in Swift, the length restriction is *after* URL encoding.
1177 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1181 * Splits a storage path into an internal container name,
1182 * an internal relative file name, and a container shard suffix.
1183 * Any shard suffix is already appended to the internal container name.
1184 * This also checks that the storage path is valid and within this backend.
1186 * If the container is sharded but a suffix could not be determined,
1187 * this means that the path can only refer to a directory and can only
1188 * be scanned by looking in all the container shards.
1190 * @param $storagePath string
1191 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1193 final protected function resolveStoragePath( $storagePath ) {
1194 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1195 if ( $backend === $this->name
) { // must be for this backend
1196 $relPath = self
::normalizeContainerPath( $relPath );
1197 if ( $relPath !== null ) {
1198 // Get shard for the normalized path if this container is sharded
1199 $cShard = $this->getContainerShard( $container, $relPath );
1200 // Validate and sanitize the relative path (backend-specific)
1201 $relPath = $this->resolveContainerPath( $container, $relPath );
1202 if ( $relPath !== null ) {
1203 // Prepend any wiki ID prefix to the container name
1204 $container = $this->fullContainerName( $container );
1205 if ( self
::isValidContainerName( $container ) ) {
1206 // Validate and sanitize the container name (backend-specific)
1207 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1208 if ( $container !== null ) {
1209 return array( $container, $relPath, $cShard );
1215 return array( null, null, null );
1219 * Like resolveStoragePath() except null values are returned if
1220 * the container is sharded and the shard could not be determined.
1222 * @see FileBackendStore::resolveStoragePath()
1224 * @param $storagePath string
1225 * @return Array (container, path) or (null, null) if invalid
1227 final protected function resolveStoragePathReal( $storagePath ) {
1228 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1229 if ( $cShard !== null ) {
1230 return array( $container, $relPath );
1232 return array( null, null );
1236 * Get the container name shard suffix for a given path.
1237 * Any empty suffix means the container is not sharded.
1239 * @param $container string Container name
1240 * @param $relPath string Storage path relative to the container
1241 * @return string|null Returns null if shard could not be determined
1243 final protected function getContainerShard( $container, $relPath ) {
1244 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1245 if ( $levels == 1 ||
$levels == 2 ) {
1246 // Hash characters are either base 16 or 36
1247 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1248 // Get a regex that represents the shard portion of paths.
1249 // The concatenation of the captures gives us the shard.
1250 if ( $levels === 1 ) { // 16 or 36 shards per container
1251 $hashDirRegex = '(' . $char . ')';
1252 } else { // 256 or 1296 shards per container
1253 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1254 $hashDirRegex = $char . '/(' . $char . '{2})';
1255 } else { // short hash dir format (e.g. "a/b/c")
1256 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1259 // Allow certain directories to be above the hash dirs so as
1260 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1261 // They must be 2+ chars to avoid any hash directory ambiguity.
1263 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1264 return '.' . implode( '', array_slice( $m, 1 ) );
1266 return null; // failed to match
1268 return ''; // no sharding
1272 * Check if a storage path maps to a single shard.
1273 * Container dirs like "a", where the container shards on "x/xy",
1274 * can reside on several shards. Such paths are tricky to handle.
1276 * @param $storagePath string Storage path
1279 final public function isSingleShardPathInternal( $storagePath ) {
1280 list( $c, $r, $shard ) = $this->resolveStoragePath( $storagePath );
1281 return ( $shard !== null );
1285 * Get the sharding config for a container.
1286 * If greater than 0, then all file storage paths within
1287 * the container are required to be hashed accordingly.
1289 * @param $container string
1290 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
1292 final protected function getContainerHashLevels( $container ) {
1293 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1294 $config = $this->shardViaHashLevels
[$container];
1295 $hashLevels = (int)$config['levels'];
1296 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1297 $hashBase = (int)$config['base'];
1298 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1299 return array( $hashLevels, $hashBase, $config['repeat'] );
1303 return array( 0, 0, false ); // no sharding
1307 * Get a list of full container shard suffixes for a container
1309 * @param $container string
1312 final protected function getContainerSuffixes( $container ) {
1314 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1315 if ( $digits > 0 ) {
1316 $numShards = pow( $base, $digits );
1317 for ( $index = 0; $index < $numShards; $index++
) {
1318 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1325 * Get the full container name, including the wiki ID prefix
1327 * @param $container string
1330 final protected function fullContainerName( $container ) {
1331 if ( $this->wikiId
!= '' ) {
1332 return "{$this->wikiId}-$container";
1339 * Resolve a container name, checking if it's allowed by the backend.
1340 * This is intended for internal use, such as encoding illegal chars.
1341 * Subclasses can override this to be more restrictive.
1343 * @param $container string
1344 * @return string|null
1346 protected function resolveContainerName( $container ) {
1351 * Resolve a relative storage path, checking if it's allowed by the backend.
1352 * This is intended for internal use, such as encoding illegal chars or perhaps
1353 * getting absolute paths (e.g. FS based backends). Note that the relative path
1354 * may be the empty string (e.g. the path is simply to the container).
1356 * @param $container string Container name
1357 * @param $relStoragePath string Storage path relative to the container
1358 * @return string|null Path or null if not valid
1360 protected function resolveContainerPath( $container, $relStoragePath ) {
1361 return $relStoragePath;
1365 * Get the cache key for a container
1367 * @param $container string Resolved container name
1370 private function containerCacheKey( $container ) {
1371 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1375 * Set the cached info for a container
1377 * @param $container string Resolved container name
1378 * @param $val mixed Information to cache
1380 final protected function setContainerCache( $container, $val ) {
1381 $this->memCache
->add( $this->containerCacheKey( $container ), $val, 14*86400 );
1385 * Delete the cached info for a container.
1386 * The cache key is salted for a while to prevent race conditions.
1388 * @param $container string Resolved container name
1390 final protected function deleteContainerCache( $container ) {
1391 if ( !$this->memCache
->set( $this->containerCacheKey( $container ), 'PURGED', 300 ) ) {
1392 trigger_error( "Unable to delete stat cache for container $container." );
1397 * Do a batch lookup from cache for container stats for all containers
1398 * used in a list of container names, storage paths, or FileOp objects.
1400 * @param $items Array
1403 final protected function primeContainerCache( array $items ) {
1404 wfProfileIn( __METHOD__
);
1405 wfProfileIn( __METHOD__
. '-' . $this->name
);
1407 $paths = array(); // list of storage paths
1408 $contNames = array(); // (cache key => resolved container name)
1409 // Get all the paths/containers from the items...
1410 foreach ( $items as $item ) {
1411 if ( $item instanceof FileOp
) {
1412 $paths = array_merge( $paths, $item->storagePathsRead() );
1413 $paths = array_merge( $paths, $item->storagePathsChanged() );
1414 } elseif ( self
::isStoragePath( $item ) ) {
1416 } elseif ( is_string( $item ) ) { // full container name
1417 $contNames[$this->containerCacheKey( $item )] = $item;
1420 // Get all the corresponding cache keys for paths...
1421 foreach ( $paths as $path ) {
1422 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1423 if ( $fullCont !== null ) { // valid path for this backend
1424 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1428 $contInfo = array(); // (resolved container name => cache value)
1429 // Get all cache entries for these container cache keys...
1430 $values = $this->memCache
->getMulti( array_keys( $contNames ) );
1431 foreach ( $values as $cacheKey => $val ) {
1432 $contInfo[$contNames[$cacheKey]] = $val;
1435 // Populate the container process cache for the backend...
1436 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1438 wfProfileOut( __METHOD__
. '-' . $this->name
);
1439 wfProfileOut( __METHOD__
);
1443 * Fill the backend-specific process cache given an array of
1444 * resolved container names and their corresponding cached info.
1445 * Only containers that actually exist should appear in the map.
1447 * @param $containerInfo Array Map of resolved container names to cached info
1450 protected function doPrimeContainerCache( array $containerInfo ) {}
1453 * Get the cache key for a file path
1455 * @param $path string Storage path
1458 private function fileCacheKey( $path ) {
1459 return wfMemcKey( 'backend', $this->getName(), 'file', sha1( $path ) );
1463 * Set the cached stat info for a file path
1465 * @param $path string Storage path
1466 * @param $val mixed Information to cache
1468 final protected function setFileCache( $path, $val ) {
1469 $this->memCache
->add( $this->fileCacheKey( $path ), $val, 7*86400 );
1473 * Delete the cached stat info for a file path.
1474 * The cache key is salted for a while to prevent race conditions.
1476 * @param $path string Storage path
1478 final protected function deleteFileCache( $path ) {
1479 if ( !$this->memCache
->set( $this->fileCacheKey( $path ), 'PURGED', 300 ) ) {
1480 trigger_error( "Unable to delete stat cache for file $path." );
1485 * Do a batch lookup from cache for file stats for all paths
1486 * used in a list of storage paths or FileOp objects.
1488 * @param $items Array List of storage paths or FileOps
1491 final protected function primeFileCache( array $items ) {
1492 wfProfileIn( __METHOD__
);
1493 wfProfileIn( __METHOD__
. '-' . $this->name
);
1495 $paths = array(); // list of storage paths
1496 $pathNames = array(); // (cache key => storage path)
1497 // Get all the paths/containers from the items...
1498 foreach ( $items as $item ) {
1499 if ( $item instanceof FileOp
) {
1500 $paths = array_merge( $paths, $item->storagePathsRead() );
1501 $paths = array_merge( $paths, $item->storagePathsChanged() );
1502 } elseif ( self
::isStoragePath( $item ) ) {
1506 // Get all the corresponding cache keys for paths...
1507 foreach ( $paths as $path ) {
1508 list( $cont, $rel, $s ) = $this->resolveStoragePath( $path );
1509 if ( $rel !== null ) { // valid path for this backend
1510 $pathNames[$this->fileCacheKey( $path )] = $path;
1513 // Get all cache entries for these container cache keys...
1514 $values = $this->memCache
->getMulti( array_keys( $pathNames ) );
1515 foreach ( $values as $cacheKey => $val ) {
1516 if ( is_array( $val ) ) {
1517 $path = $pathNames[$cacheKey];
1518 $this->cheapCache
->set( $path, 'stat', $val );
1519 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1520 $this->cheapCache
->set( $path, 'sha1',
1521 array( 'hash' => $val['sha1'], 'latest' => $val['latest'] ) );
1526 wfProfileOut( __METHOD__
. '-' . $this->name
);
1527 wfProfileOut( __METHOD__
);
1532 * FileBackendStore helper class for performing asynchronous file operations.
1534 * For example, calling FileBackendStore::createInternal() with the "async"
1535 * param flag may result in a Status that contains this object as a value.
1536 * This class is largely backend-specific and is mostly just "magic" to be
1537 * passed to FileBackendStore::executeOpHandlesInternal().
1539 abstract class FileBackendStoreOpHandle
{
1541 public $params = array(); // params to caller functions
1542 /** @var FileBackendStore */
1545 public $resourcesToClose = array();
1547 public $call; // string; name that identifies the function called
1550 * Close all open file handles
1554 public function closeResources() {
1555 array_map( 'fclose', $this->resourcesToClose
);
1560 * FileBackendStore helper function to handle listings that span container shards.
1561 * Do not use this class from places outside of FileBackendStore.
1563 * @ingroup FileBackend
1565 abstract class FileBackendStoreShardListIterator
implements Iterator
{
1566 /** @var FileBackendStore */
1571 protected $shardSuffixes;
1572 protected $container; // string; full container name
1573 protected $directory; // string; resolved relative path
1575 /** @var Traversable */
1577 protected $curShard = 0; // integer
1578 protected $pos = 0; // integer
1581 protected $multiShardPaths = array(); // (rel path => 1)
1584 * @param $backend FileBackendStore
1585 * @param $container string Full storage container name
1586 * @param $dir string Storage directory relative to container
1587 * @param $suffixes Array List of container shard suffixes
1588 * @param $params Array
1590 public function __construct(
1591 FileBackendStore
$backend, $container, $dir, array $suffixes, array $params
1593 $this->backend
= $backend;
1594 $this->container
= $container;
1595 $this->directory
= $dir;
1596 $this->shardSuffixes
= $suffixes;
1597 $this->params
= $params;
1601 * @see Iterator::key()
1604 public function key() {
1609 * @see Iterator::valid()
1612 public function valid() {
1613 if ( $this->iter
instanceof Iterator
) {
1614 return $this->iter
->valid();
1615 } elseif ( is_array( $this->iter
) ) {
1616 return ( current( $this->iter
) !== false ); // no paths can have this value
1618 return false; // some failure?
1622 * @see Iterator::current()
1623 * @return string|bool String or false
1625 public function current() {
1626 return ( $this->iter
instanceof Iterator
)
1627 ?
$this->iter
->current()
1628 : current( $this->iter
);
1632 * @see Iterator::next()
1635 public function next() {
1637 ( $this->iter
instanceof Iterator
) ?
$this->iter
->next() : next( $this->iter
);
1639 $continue = false; // keep scanning shards?
1640 $this->filterViaNext(); // filter out duplicates
1641 // Find the next non-empty shard if no elements are left
1642 if ( !$this->valid() ) {
1643 $this->nextShardIteratorIfNotValid();
1644 $continue = $this->valid(); // re-filter unless we ran out of shards
1646 } while ( $continue );
1650 * @see Iterator::rewind()
1653 public function rewind() {
1655 $this->curShard
= 0;
1656 $this->setIteratorFromCurrentShard();
1658 $continue = false; // keep scanning shards?
1659 $this->filterViaNext(); // filter out duplicates
1660 // Find the next non-empty shard if no elements are left
1661 if ( !$this->valid() ) {
1662 $this->nextShardIteratorIfNotValid();
1663 $continue = $this->valid(); // re-filter unless we ran out of shards
1665 } while ( $continue );
1669 * Filter out duplicate items by advancing to the next ones
1671 protected function filterViaNext() {
1672 while ( $this->valid() ) {
1673 $rel = $this->iter
->current(); // path relative to given directory
1674 $path = $this->params
['dir'] . "/{$rel}"; // full storage path
1675 if ( $this->backend
->isSingleShardPathInternal( $path ) ) {
1676 break; // path is only on one shard; no issue with duplicates
1677 } elseif ( isset( $this->multiShardPaths
[$rel] ) ) {
1678 // Don't keep listing paths that are on multiple shards
1679 ( $this->iter
instanceof Iterator
) ?
$this->iter
->next() : next( $this->iter
);
1681 $this->multiShardPaths
[$rel] = 1;
1688 * If the list iterator for this container shard is out of items,
1689 * then move on to the next container that has items.
1690 * If there are none, then it advances to the last container.
1692 protected function nextShardIteratorIfNotValid() {
1693 while ( !$this->valid() && ++
$this->curShard
< count( $this->shardSuffixes
) ) {
1694 $this->setIteratorFromCurrentShard();
1699 * Set the list iterator to that of the current container shard
1701 protected function setIteratorFromCurrentShard() {
1702 $this->iter
= $this->listFromShard(
1703 $this->container
. $this->shardSuffixes
[$this->curShard
],
1704 $this->directory
, $this->params
);
1705 // Start loading results so that current() works
1706 if ( $this->iter
) {
1707 ( $this->iter
instanceof Iterator
) ?
$this->iter
->rewind() : reset( $this->iter
);
1712 * Get the list for a given container shard
1714 * @param $container string Resolved container name
1715 * @param $dir string Resolved path relative to container
1716 * @param $params Array
1717 * @return Traversable|Array|null
1719 abstract protected function listFromShard( $container, $dir, array $params );
1723 * Iterator for listing directories
1725 class FileBackendStoreShardDirIterator
extends FileBackendStoreShardListIterator
{
1727 * @see FileBackendStoreShardListIterator::listFromShard()
1728 * @return Array|null|Traversable
1730 protected function listFromShard( $container, $dir, array $params ) {
1731 return $this->backend
->getDirectoryListInternal( $container, $dir, $params );
1736 * Iterator for listing regular files
1738 class FileBackendStoreShardFileIterator
extends FileBackendStoreShardListIterator
{
1740 * @see FileBackendStoreShardListIterator::listFromShard()
1741 * @return Array|null|Traversable
1743 protected function listFromShard( $container, $dir, array $params ) {
1744 return $this->backend
->getFileListInternal( $container, $dir, $params );