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)
51 const CACHE_TTL
= 10; // integer; TTL in seconds for process cache entries
54 * @see FileBackend::__construct()
56 * @param $config Array
58 public function __construct( array $config ) {
59 parent
::__construct( $config );
60 $this->memCache
= new EmptyBagOStuff(); // disabled by default
61 $this->cheapCache
= new ProcessCacheLRU( 300 );
62 $this->expensiveCache
= new ProcessCacheLRU( 5 );
66 * Get the maximum allowable file size given backend
67 * medium restrictions and basic performance constraints.
68 * Do not call this function from places outside FileBackend and FileOp.
70 * @return integer Bytes
72 final public function maxFileSizeInternal() {
73 return $this->maxFileSize
;
77 * Check if a file can be created or changed at a given storage path.
78 * FS backends should check if the parent directory exists, files can be
79 * written under it, and that any file already there is writable.
80 * Backends using key/value stores should check if the container exists.
82 * @param $storagePath string
85 abstract public function isPathUsableInternal( $storagePath );
88 * Create a file in the backend with the given contents.
89 * This will overwrite any file that exists at the destination.
90 * Do not call this function from places outside FileBackend and FileOp.
93 * - content : the raw file contents
94 * - dst : destination storage path
95 * - disposition : Content-Disposition header value for the destination
96 * - headers : HTTP header name/value map
97 * - async : Status will be returned immediately if supported.
98 * If the status is OK, then its value field will be
99 * set to a FileBackendStoreOpHandle object.
101 * @param $params Array
104 final public function createInternal( array $params ) {
105 wfProfileIn( __METHOD__
);
106 wfProfileIn( __METHOD__
. '-' . $this->name
);
107 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
108 $status = Status
::newFatal( 'backend-fail-maxsize',
109 $params['dst'], $this->maxFileSizeInternal() );
111 $status = $this->doCreateInternal( $params );
112 $this->clearCache( array( $params['dst'] ) );
113 $this->deleteFileCache( $params['dst'] ); // persistent cache
115 wfProfileOut( __METHOD__
. '-' . $this->name
);
116 wfProfileOut( __METHOD__
);
121 * @see FileBackendStore::createInternal()
123 abstract protected function doCreateInternal( array $params );
126 * Store a file into the backend from a file on disk.
127 * This will overwrite any file that exists at the destination.
128 * Do not call this function from places outside FileBackend and FileOp.
131 * - src : source path on disk
132 * - dst : destination storage path
133 * - disposition : Content-Disposition header value for the destination
134 * - headers : HTTP header name/value map
135 * - async : Status will be returned immediately if supported.
136 * If the status is OK, then its value field will be
137 * set to a FileBackendStoreOpHandle object.
139 * @param $params Array
142 final public function storeInternal( array $params ) {
143 wfProfileIn( __METHOD__
);
144 wfProfileIn( __METHOD__
. '-' . $this->name
);
145 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
146 $status = Status
::newFatal( 'backend-fail-maxsize',
147 $params['dst'], $this->maxFileSizeInternal() );
149 $status = $this->doStoreInternal( $params );
150 $this->clearCache( array( $params['dst'] ) );
151 $this->deleteFileCache( $params['dst'] ); // persistent cache
153 wfProfileOut( __METHOD__
. '-' . $this->name
);
154 wfProfileOut( __METHOD__
);
159 * @see FileBackendStore::storeInternal()
161 abstract protected function doStoreInternal( array $params );
164 * Copy a file from one storage path to another in the backend.
165 * This will overwrite any file that exists at the destination.
166 * Do not call this function from places outside FileBackend and FileOp.
169 * - src : source storage path
170 * - dst : destination storage path
171 * - ignoreMissingSource : do nothing if the source file does not exist
172 * - disposition : Content-Disposition header value for the destination
173 * - async : Status will be returned immediately if supported.
174 * If the status is OK, then its value field will be
175 * set to a FileBackendStoreOpHandle object.
177 * @param $params Array
180 final public function copyInternal( array $params ) {
181 wfProfileIn( __METHOD__
);
182 wfProfileIn( __METHOD__
. '-' . $this->name
);
183 $status = $this->doCopyInternal( $params );
184 $this->clearCache( array( $params['dst'] ) );
185 $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 * This will overwrite any file that exists at the destination.
229 * Do not call this function from places outside FileBackend and FileOp.
232 * - src : source storage path
233 * - dst : destination storage path
234 * - ignoreMissingSource : do nothing if the source file does not exist
235 * - disposition : Content-Disposition header value for the destination
236 * - async : Status will be returned immediately if supported.
237 * If the status is OK, then its value field will be
238 * set to a FileBackendStoreOpHandle object.
240 * @param $params Array
243 final public function moveInternal( array $params ) {
244 wfProfileIn( __METHOD__
);
245 wfProfileIn( __METHOD__
. '-' . $this->name
);
246 $status = $this->doMoveInternal( $params );
247 $this->clearCache( array( $params['src'], $params['dst'] ) );
248 $this->deleteFileCache( $params['src'] ); // persistent cache
249 $this->deleteFileCache( $params['dst'] ); // persistent cache
250 wfProfileOut( __METHOD__
. '-' . $this->name
);
251 wfProfileOut( __METHOD__
);
256 * @see FileBackendStore::moveInternal()
259 protected function doMoveInternal( array $params ) {
260 unset( $params['async'] ); // two steps, won't work here :)
261 // Copy source to dest
262 $status = $this->copyInternal( $params );
263 if ( $status->isOK() ) {
264 // Delete source (only fails due to races or medium going down)
265 $status->merge( $this->deleteInternal( array( 'src' => $params['src'] ) ) );
266 $status->setResult( true, $status->value
); // ignore delete() errors
272 * No-op file operation that does nothing.
273 * Do not call this function from places outside FileBackend and FileOp.
275 * @param $params Array
278 final public function nullInternal( array $params ) {
279 return Status
::newGood();
283 * @see FileBackend::concatenate()
286 final public function concatenate( array $params ) {
287 wfProfileIn( __METHOD__
);
288 wfProfileIn( __METHOD__
. '-' . $this->name
);
289 $status = Status
::newGood();
291 // Try to lock the source files for the scope of this function
292 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager
::LOCK_UW
, $status );
293 if ( $status->isOK() ) {
294 // Actually do the file concatenation...
295 $start_time = microtime( true );
296 $status->merge( $this->doConcatenate( $params ) );
297 $sec = microtime( true ) - $start_time;
298 if ( !$status->isOK() ) {
299 wfDebugLog( 'FileOperation', get_class( $this ) . " failed to concatenate " .
300 count( $params['srcs'] ) . " file(s) [$sec sec]" );
304 wfProfileOut( __METHOD__
. '-' . $this->name
);
305 wfProfileOut( __METHOD__
);
310 * @see FileBackendStore::concatenate()
313 protected function doConcatenate( array $params ) {
314 $status = Status
::newGood();
315 $tmpPath = $params['dst']; // convenience
316 unset( $params['latest'] ); // sanity
318 // Check that the specified temp file is valid...
319 wfSuppressWarnings();
320 $ok = ( is_file( $tmpPath ) && filesize( $tmpPath ) == 0 );
322 if ( !$ok ) { // not present or not empty
323 $status->fatal( 'backend-fail-opentemp', $tmpPath );
327 // Get local FS versions of the chunks needed for the concatenation...
328 $fsFiles = $this->getLocalReferenceMulti( $params );
329 foreach ( $fsFiles as $path => &$fsFile ) {
330 if ( !$fsFile ) { // chunk failed to download?
331 $fsFile = $this->getLocalReference( array( 'src' => $path ) );
332 if ( !$fsFile ) { // retry failed?
333 $status->fatal( 'backend-fail-read', $path );
338 unset( $fsFile ); // unset reference so we can reuse $fsFile
340 // Get a handle for the destination temp file
341 $tmpHandle = fopen( $tmpPath, 'ab' );
342 if ( $tmpHandle === false ) {
343 $status->fatal( 'backend-fail-opentemp', $tmpPath );
347 // Build up the temp file using the source chunks (in order)...
348 foreach ( $fsFiles as $virtualSource => $fsFile ) {
349 // Get a handle to the local FS version
350 $sourceHandle = fopen( $fsFile->getPath(), 'rb' );
351 if ( $sourceHandle === false ) {
352 fclose( $tmpHandle );
353 $status->fatal( 'backend-fail-read', $virtualSource );
356 // Append chunk to file (pass chunk size to avoid magic quotes)
357 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
358 fclose( $sourceHandle );
359 fclose( $tmpHandle );
360 $status->fatal( 'backend-fail-writetemp', $tmpPath );
363 fclose( $sourceHandle );
365 if ( !fclose( $tmpHandle ) ) {
366 $status->fatal( 'backend-fail-closetemp', $tmpPath );
370 clearstatcache(); // temp file changed
376 * @see FileBackend::doPrepare()
379 final protected function doPrepare( array $params ) {
380 wfProfileIn( __METHOD__
);
381 wfProfileIn( __METHOD__
. '-' . $this->name
);
383 $status = Status
::newGood();
384 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
385 if ( $dir === null ) {
386 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
387 wfProfileOut( __METHOD__
. '-' . $this->name
);
388 wfProfileOut( __METHOD__
);
389 return $status; // invalid storage path
392 if ( $shard !== null ) { // confined to a single container/shard
393 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
394 } else { // directory is on several shards
395 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
396 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
397 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
398 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
402 wfProfileOut( __METHOD__
. '-' . $this->name
);
403 wfProfileOut( __METHOD__
);
408 * @see FileBackendStore::doPrepare()
411 protected function doPrepareInternal( $container, $dir, array $params ) {
412 return Status
::newGood();
416 * @see FileBackend::doSecure()
419 final protected function doSecure( array $params ) {
420 wfProfileIn( __METHOD__
);
421 wfProfileIn( __METHOD__
. '-' . $this->name
);
422 $status = Status
::newGood();
424 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
425 if ( $dir === null ) {
426 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
427 wfProfileOut( __METHOD__
. '-' . $this->name
);
428 wfProfileOut( __METHOD__
);
429 return $status; // invalid storage path
432 if ( $shard !== null ) { // confined to a single container/shard
433 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
434 } else { // directory is on several shards
435 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
436 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
437 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
438 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
442 wfProfileOut( __METHOD__
. '-' . $this->name
);
443 wfProfileOut( __METHOD__
);
448 * @see FileBackendStore::doSecure()
451 protected function doSecureInternal( $container, $dir, array $params ) {
452 return Status
::newGood();
456 * @see FileBackend::doPublish()
459 final protected function doPublish( array $params ) {
460 wfProfileIn( __METHOD__
);
461 wfProfileIn( __METHOD__
. '-' . $this->name
);
462 $status = Status
::newGood();
464 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
465 if ( $dir === null ) {
466 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
467 wfProfileOut( __METHOD__
. '-' . $this->name
);
468 wfProfileOut( __METHOD__
);
469 return $status; // invalid storage path
472 if ( $shard !== null ) { // confined to a single container/shard
473 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
474 } else { // directory is on several shards
475 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
476 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
477 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
478 $status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
482 wfProfileOut( __METHOD__
. '-' . $this->name
);
483 wfProfileOut( __METHOD__
);
488 * @see FileBackendStore::doPublish()
491 protected function doPublishInternal( $container, $dir, array $params ) {
492 return Status
::newGood();
496 * @see FileBackend::doClean()
499 final protected function doClean( array $params ) {
500 wfProfileIn( __METHOD__
);
501 wfProfileIn( __METHOD__
. '-' . $this->name
);
502 $status = Status
::newGood();
504 // Recursive: first delete all empty subdirs recursively
505 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
506 $subDirsRel = $this->getTopDirectoryList( array( 'dir' => $params['dir'] ) );
507 if ( $subDirsRel !== null ) { // no errors
508 foreach ( $subDirsRel as $subDirRel ) {
509 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
510 $status->merge( $this->doClean( array( 'dir' => $subDir ) +
$params ) );
512 unset( $subDirsRel ); // free directory for rmdir() on Windows (for FS backends)
516 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
517 if ( $dir === null ) {
518 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
519 wfProfileOut( __METHOD__
. '-' . $this->name
);
520 wfProfileOut( __METHOD__
);
521 return $status; // invalid storage path
524 // Attempt to lock this directory...
525 $filesLockEx = array( $params['dir'] );
526 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
527 if ( !$status->isOK() ) {
528 wfProfileOut( __METHOD__
. '-' . $this->name
);
529 wfProfileOut( __METHOD__
);
530 return $status; // abort
533 if ( $shard !== null ) { // confined to a single container/shard
534 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
535 $this->deleteContainerCache( $fullCont ); // purge cache
536 } else { // directory is on several shards
537 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
538 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
539 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
540 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
541 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
545 wfProfileOut( __METHOD__
. '-' . $this->name
);
546 wfProfileOut( __METHOD__
);
551 * @see FileBackendStore::doClean()
554 protected function doCleanInternal( $container, $dir, array $params ) {
555 return Status
::newGood();
559 * @see FileBackend::fileExists()
562 final public function fileExists( array $params ) {
563 wfProfileIn( __METHOD__
);
564 wfProfileIn( __METHOD__
. '-' . $this->name
);
565 $stat = $this->getFileStat( $params );
566 wfProfileOut( __METHOD__
. '-' . $this->name
);
567 wfProfileOut( __METHOD__
);
568 return ( $stat === null ) ?
null : (bool)$stat; // null => failure
572 * @see FileBackend::getFileTimestamp()
575 final public function getFileTimestamp( array $params ) {
576 wfProfileIn( __METHOD__
);
577 wfProfileIn( __METHOD__
. '-' . $this->name
);
578 $stat = $this->getFileStat( $params );
579 wfProfileOut( __METHOD__
. '-' . $this->name
);
580 wfProfileOut( __METHOD__
);
581 return $stat ?
$stat['mtime'] : false;
585 * @see FileBackend::getFileSize()
588 final public function getFileSize( array $params ) {
589 wfProfileIn( __METHOD__
);
590 wfProfileIn( __METHOD__
. '-' . $this->name
);
591 $stat = $this->getFileStat( $params );
592 wfProfileOut( __METHOD__
. '-' . $this->name
);
593 wfProfileOut( __METHOD__
);
594 return $stat ?
$stat['size'] : false;
598 * @see FileBackend::getFileStat()
601 final public function getFileStat( array $params ) {
602 $path = self
::normalizeStoragePath( $params['src'] );
603 if ( $path === null ) {
604 return false; // invalid storage path
606 wfProfileIn( __METHOD__
);
607 wfProfileIn( __METHOD__
. '-' . $this->name
);
608 $latest = !empty( $params['latest'] ); // use latest data?
609 if ( !$this->cheapCache
->has( $path, 'stat', self
::CACHE_TTL
) ) {
610 $this->primeFileCache( array( $path ) ); // check persistent cache
612 if ( $this->cheapCache
->has( $path, 'stat', self
::CACHE_TTL
) ) {
613 $stat = $this->cheapCache
->get( $path, 'stat' );
614 // If we want the latest data, check that this cached
615 // value was in fact fetched with the latest available data
616 // (the process cache is ignored if it contains a negative).
617 if ( !$latest ||
( is_array( $stat ) && $stat['latest'] ) ) {
618 wfProfileOut( __METHOD__
. '-' . $this->name
);
619 wfProfileOut( __METHOD__
);
623 wfProfileIn( __METHOD__
. '-miss' );
624 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
625 $stat = $this->doGetFileStat( $params );
626 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
627 wfProfileOut( __METHOD__
. '-miss' );
628 if ( is_array( $stat ) ) { // file exists
629 $stat['latest'] = $latest;
630 $this->cheapCache
->set( $path, 'stat', $stat );
631 $this->setFileCache( $path, $stat ); // update persistent cache
632 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
633 $this->cheapCache
->set( $path, 'sha1',
634 array( 'hash' => $stat['sha1'], 'latest' => $latest ) );
636 } elseif ( $stat === false ) { // file does not exist
637 $this->cheapCache
->set( $path, 'stat', false );
638 wfDebug( __METHOD__
. ": File $path does not exist.\n" );
639 } else { // an error occurred
640 wfDebug( __METHOD__
. ": Could not stat file $path.\n" );
642 wfProfileOut( __METHOD__
. '-' . $this->name
);
643 wfProfileOut( __METHOD__
);
648 * @see FileBackendStore::getFileStat()
650 abstract protected function doGetFileStat( array $params );
653 * @see FileBackend::getFileContentsMulti()
656 public function getFileContentsMulti( array $params ) {
657 wfProfileIn( __METHOD__
);
658 wfProfileIn( __METHOD__
. '-' . $this->name
);
660 $params = $this->setConcurrencyFlags( $params );
661 $contents = $this->doGetFileContentsMulti( $params );
663 wfProfileOut( __METHOD__
. '-' . $this->name
);
664 wfProfileOut( __METHOD__
);
669 * @see FileBackendStore::getFileContentsMulti()
672 protected function doGetFileContentsMulti( array $params ) {
674 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
675 wfSuppressWarnings();
676 $contents[$path] = $fsFile ?
file_get_contents( $fsFile->getPath() ) : false;
683 * @see FileBackend::getFileSha1Base36()
684 * @return bool|string
686 final public function getFileSha1Base36( array $params ) {
687 $path = self
::normalizeStoragePath( $params['src'] );
688 if ( $path === null ) {
689 return false; // invalid storage path
691 wfProfileIn( __METHOD__
);
692 wfProfileIn( __METHOD__
. '-' . $this->name
);
693 $latest = !empty( $params['latest'] ); // use latest data?
694 if ( $this->cheapCache
->has( $path, 'sha1', self
::CACHE_TTL
) ) {
695 $stat = $this->cheapCache
->get( $path, 'sha1' );
696 // If we want the latest data, check that this cached
697 // value was in fact fetched with the latest available data.
698 if ( !$latest ||
$stat['latest'] ) {
699 wfProfileOut( __METHOD__
. '-' . $this->name
);
700 wfProfileOut( __METHOD__
);
701 return $stat['hash'];
704 wfProfileIn( __METHOD__
. '-miss' );
705 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
706 $hash = $this->doGetFileSha1Base36( $params );
707 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
708 wfProfileOut( __METHOD__
. '-miss' );
709 if ( $hash ) { // don't cache negatives
710 $this->cheapCache
->set( $path, 'sha1',
711 array( 'hash' => $hash, 'latest' => $latest ) );
713 wfProfileOut( __METHOD__
. '-' . $this->name
);
714 wfProfileOut( __METHOD__
);
719 * @see FileBackendStore::getFileSha1Base36()
720 * @return bool|string
722 protected function doGetFileSha1Base36( array $params ) {
723 $fsFile = $this->getLocalReference( $params );
727 return $fsFile->getSha1Base36();
732 * @see FileBackend::getFileProps()
735 final public function getFileProps( array $params ) {
736 wfProfileIn( __METHOD__
);
737 wfProfileIn( __METHOD__
. '-' . $this->name
);
738 $fsFile = $this->getLocalReference( $params );
739 $props = $fsFile ?
$fsFile->getProps() : FSFile
::placeholderProps();
740 wfProfileOut( __METHOD__
. '-' . $this->name
);
741 wfProfileOut( __METHOD__
);
746 * @see FileBackend::getLocalReferenceMulti()
749 final public function getLocalReferenceMulti( array $params ) {
750 wfProfileIn( __METHOD__
);
751 wfProfileIn( __METHOD__
. '-' . $this->name
);
753 $params = $this->setConcurrencyFlags( $params );
755 $fsFiles = array(); // (path => FSFile)
756 $latest = !empty( $params['latest'] ); // use latest data?
757 // Reuse any files already in process cache...
758 foreach ( $params['srcs'] as $src ) {
759 $path = self
::normalizeStoragePath( $src );
760 if ( $path === null ) {
761 $fsFiles[$src] = null; // invalid storage path
762 } elseif ( $this->expensiveCache
->has( $path, 'localRef' ) ) {
763 $val = $this->expensiveCache
->get( $path, 'localRef' );
764 // If we want the latest data, check that this cached
765 // value was in fact fetched with the latest available data.
766 if ( !$latest ||
$val['latest'] ) {
767 $fsFiles[$src] = $val['object'];
771 // Fetch local references of any remaning files...
772 $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
773 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
774 $fsFiles[$path] = $fsFile;
775 if ( $fsFile ) { // update the process cache...
776 $this->expensiveCache
->set( $path, 'localRef',
777 array( 'object' => $fsFile, 'latest' => $latest ) );
781 wfProfileOut( __METHOD__
. '-' . $this->name
);
782 wfProfileOut( __METHOD__
);
787 * @see FileBackendStore::getLocalReferenceMulti()
790 protected function doGetLocalReferenceMulti( array $params ) {
791 return $this->doGetLocalCopyMulti( $params );
795 * @see FileBackend::getLocalCopyMulti()
798 final public function getLocalCopyMulti( array $params ) {
799 wfProfileIn( __METHOD__
);
800 wfProfileIn( __METHOD__
. '-' . $this->name
);
802 $params = $this->setConcurrencyFlags( $params );
803 $tmpFiles = $this->doGetLocalCopyMulti( $params );
805 wfProfileOut( __METHOD__
. '-' . $this->name
);
806 wfProfileOut( __METHOD__
);
811 * @see FileBackendStore::getLocalCopyMulti()
814 abstract protected function doGetLocalCopyMulti( array $params );
817 * @see FileBackend::getFileHttpUrl()
818 * @return string|null
820 public function getFileHttpUrl( array $params ) {
821 return null; // not supported
825 * @see FileBackend::streamFile()
828 final public function streamFile( array $params ) {
829 wfProfileIn( __METHOD__
);
830 wfProfileIn( __METHOD__
. '-' . $this->name
);
831 $status = Status
::newGood();
833 $info = $this->getFileStat( $params );
834 if ( !$info ) { // let StreamFile handle the 404
835 $status->fatal( 'backend-fail-notexists', $params['src'] );
838 // Set output buffer and HTTP headers for stream
839 $extraHeaders = isset( $params['headers'] ) ?
$params['headers'] : array();
840 $res = StreamFile
::prepareForStream( $params['src'], $info, $extraHeaders );
841 if ( $res == StreamFile
::NOT_MODIFIED
) {
842 // do nothing; client cache is up to date
843 } elseif ( $res == StreamFile
::READY_STREAM
) {
844 wfProfileIn( __METHOD__
. '-send' );
845 wfProfileIn( __METHOD__
. '-send-' . $this->name
);
846 $status = $this->doStreamFile( $params );
847 wfProfileOut( __METHOD__
. '-send-' . $this->name
);
848 wfProfileOut( __METHOD__
. '-send' );
849 if ( !$status->isOK() ) {
850 // Per bug 41113, nasty things can happen if bad cache entries get
851 // stuck in cache. It's also possible that this error can come up
852 // with simple race conditions. Clear out the stat cache to be safe.
853 $this->clearCache( array( $params['src'] ) );
854 $this->deleteFileCache( $params['src'] );
855 trigger_error( "Bad stat cache or race condition for file {$params['src']}." );
858 $status->fatal( 'backend-fail-stream', $params['src'] );
861 wfProfileOut( __METHOD__
. '-' . $this->name
);
862 wfProfileOut( __METHOD__
);
867 * @see FileBackendStore::streamFile()
870 protected function doStreamFile( array $params ) {
871 $status = Status
::newGood();
873 $fsFile = $this->getLocalReference( $params );
875 $status->fatal( 'backend-fail-stream', $params['src'] );
876 } elseif ( !readfile( $fsFile->getPath() ) ) {
877 $status->fatal( 'backend-fail-stream', $params['src'] );
884 * @see FileBackend::directoryExists()
887 final public function directoryExists( array $params ) {
888 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
889 if ( $dir === null ) {
890 return false; // invalid storage path
892 if ( $shard !== null ) { // confined to a single container/shard
893 return $this->doDirectoryExists( $fullCont, $dir, $params );
894 } else { // directory is on several shards
895 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
896 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
897 $res = false; // response
898 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
899 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
903 } elseif ( $exists === null ) { // error?
904 $res = null; // if we don't find anything, it is indeterminate
912 * @see FileBackendStore::directoryExists()
914 * @param $container string Resolved container name
915 * @param $dir string Resolved path relative to container
916 * @param $params Array
919 abstract protected function doDirectoryExists( $container, $dir, array $params );
922 * @see FileBackend::getDirectoryList()
923 * @return Traversable|Array|null Returns null on failure
925 final public function getDirectoryList( array $params ) {
926 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
927 if ( $dir === null ) { // invalid storage path
930 if ( $shard !== null ) {
931 // File listing is confined to a single container/shard
932 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
934 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
935 // File listing spans multiple containers/shards
936 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
937 return new FileBackendStoreShardDirIterator( $this,
938 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
943 * Do not call this function from places outside FileBackend
945 * @see FileBackendStore::getDirectoryList()
947 * @param $container string Resolved container name
948 * @param $dir string Resolved path relative to container
949 * @param $params Array
950 * @return Traversable|Array|null Returns null on failure
952 abstract public function getDirectoryListInternal( $container, $dir, array $params );
955 * @see FileBackend::getFileList()
956 * @return Traversable|Array|null Returns null on failure
958 final public function getFileList( array $params ) {
959 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
960 if ( $dir === null ) { // invalid storage path
963 if ( $shard !== null ) {
964 // File listing is confined to a single container/shard
965 return $this->getFileListInternal( $fullCont, $dir, $params );
967 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
968 // File listing spans multiple containers/shards
969 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
970 return new FileBackendStoreShardFileIterator( $this,
971 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
976 * Do not call this function from places outside FileBackend
978 * @see FileBackendStore::getFileList()
980 * @param $container string Resolved container name
981 * @param $dir string Resolved path relative to container
982 * @param $params Array
983 * @return Traversable|Array|null Returns null on failure
985 abstract public function getFileListInternal( $container, $dir, array $params );
988 * Return a list of FileOp objects from a list of operations.
989 * Do not call this function from places outside FileBackend.
991 * The result must have the same number of items as the input.
992 * An exception is thrown if an unsupported operation is requested.
994 * @param $ops Array Same format as doOperations()
995 * @return Array List of FileOp objects
996 * @throws MWException
998 final public function getOperationsInternal( array $ops ) {
999 $supportedOps = array(
1000 'store' => 'StoreFileOp',
1001 'copy' => 'CopyFileOp',
1002 'move' => 'MoveFileOp',
1003 'delete' => 'DeleteFileOp',
1004 'create' => 'CreateFileOp',
1005 'null' => 'NullFileOp'
1008 $performOps = array(); // array of FileOp objects
1009 // Build up ordered array of FileOps...
1010 foreach ( $ops as $operation ) {
1011 $opName = $operation['op'];
1012 if ( isset( $supportedOps[$opName] ) ) {
1013 $class = $supportedOps[$opName];
1014 // Get params for this operation
1015 $params = $operation;
1016 // Append the FileOp class
1017 $performOps[] = new $class( $this, $params );
1019 throw new MWException( "Operation '$opName' is not supported." );
1027 * Get a list of storage paths to lock for a list of operations
1028 * Returns an array with 'sh' (shared) and 'ex' (exclusive) keys,
1029 * each corresponding to a list of storage paths to be locked.
1030 * All returned paths are normalized.
1032 * @param $performOps Array List of FileOp objects
1033 * @return Array ('sh' => list of paths, 'ex' => list of paths)
1035 final public function getPathsToLockForOpsInternal( array $performOps ) {
1036 // Build up a list of files to lock...
1037 $paths = array( 'sh' => array(), 'ex' => array() );
1038 foreach ( $performOps as $fileOp ) {
1039 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1040 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1042 // Optimization: if doing an EX lock anyway, don't also set an SH one
1043 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1044 // Get a shared lock on the parent directory of each path changed
1045 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1051 * @see FileBackend::getScopedLocksForOps()
1054 public function getScopedLocksForOps( array $ops, Status
$status ) {
1055 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1057 $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status ),
1058 $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status )
1063 * @see FileBackend::doOperationsInternal()
1066 final protected function doOperationsInternal( array $ops, array $opts ) {
1067 wfProfileIn( __METHOD__
);
1068 wfProfileIn( __METHOD__
. '-' . $this->name
);
1069 $status = Status
::newGood();
1071 // Fix up custom header name/value pairs...
1072 $ops = array_map( array( $this, 'stripInvalidHeadersFromOp' ), $ops );
1074 // Build up a list of FileOps...
1075 $performOps = $this->getOperationsInternal( $ops );
1077 // Acquire any locks as needed...
1078 if ( empty( $opts['nonLocking'] ) ) {
1079 // Build up a list of files to lock...
1080 $paths = $this->getPathsToLockForOpsInternal( $performOps );
1081 // Try to lock those files for the scope of this function...
1082 $scopeLockS = $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status );
1083 $scopeLockE = $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status );
1084 if ( !$status->isOK() ) {
1085 wfProfileOut( __METHOD__
. '-' . $this->name
);
1086 wfProfileOut( __METHOD__
);
1087 return $status; // abort
1091 // Clear any file cache entries (after locks acquired)
1092 if ( empty( $opts['preserveCache'] ) ) {
1093 $this->clearCache();
1096 // Load from the persistent file and container caches
1097 $this->primeFileCache( $performOps );
1098 $this->primeContainerCache( $performOps );
1100 // Actually attempt the operation batch...
1101 $opts = $this->setConcurrencyFlags( $opts );
1102 $subStatus = FileOpBatch
::attempt( $performOps, $opts, $this->fileJournal
);
1104 // Merge errors into status fields
1105 $status->merge( $subStatus );
1106 $status->success
= $subStatus->success
; // not done in merge()
1108 wfProfileOut( __METHOD__
. '-' . $this->name
);
1109 wfProfileOut( __METHOD__
);
1114 * @see FileBackend::doQuickOperationsInternal()
1116 * @throws MWException
1118 final protected function doQuickOperationsInternal( array $ops ) {
1119 wfProfileIn( __METHOD__
);
1120 wfProfileIn( __METHOD__
. '-' . $this->name
);
1121 $status = Status
::newGood();
1123 // Fix up custom header name/value pairs...
1124 $ops = array_map( array( $this, 'stripInvalidHeadersFromOp' ), $ops );
1126 $supportedOps = array( 'create', 'store', 'copy', 'move', 'delete', 'null' );
1127 $async = ( $this->parallelize
=== 'implicit' );
1128 $maxConcurrency = $this->concurrency
; // throttle
1130 $statuses = array(); // array of (index => Status)
1131 $fileOpHandles = array(); // list of (index => handle) arrays
1132 $curFileOpHandles = array(); // current handle batch
1133 // Perform the sync-only ops and build up op handles for the async ops...
1134 foreach ( $ops as $index => $params ) {
1135 if ( !in_array( $params['op'], $supportedOps ) ) {
1136 wfProfileOut( __METHOD__
. '-' . $this->name
);
1137 wfProfileOut( __METHOD__
);
1138 throw new MWException( "Operation '{$params['op']}' is not supported." );
1140 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1141 $subStatus = $this->$method( array( 'async' => $async ) +
$params );
1142 if ( $subStatus->value
instanceof FileBackendStoreOpHandle
) { // async
1143 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1144 $fileOpHandles[] = $curFileOpHandles; // push this batch
1145 $curFileOpHandles = array();
1147 $curFileOpHandles[$index] = $subStatus->value
; // keep index
1148 } else { // error or completed
1149 $statuses[$index] = $subStatus; // keep index
1152 if ( count( $curFileOpHandles ) ) {
1153 $fileOpHandles[] = $curFileOpHandles; // last batch
1155 // Do all the async ops that can be done concurrently...
1156 foreach ( $fileOpHandles as $fileHandleBatch ) {
1157 $statuses = $statuses +
$this->executeOpHandlesInternal( $fileHandleBatch );
1159 // Marshall and merge all the responses...
1160 foreach ( $statuses as $index => $subStatus ) {
1161 $status->merge( $subStatus );
1162 if ( $subStatus->isOK() ) {
1163 $status->success
[$index] = true;
1164 ++
$status->successCount
;
1166 $status->success
[$index] = false;
1167 ++
$status->failCount
;
1171 wfProfileOut( __METHOD__
. '-' . $this->name
);
1172 wfProfileOut( __METHOD__
);
1177 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1178 * The resulting Status object fields will correspond
1179 * to the order in which the handles where given.
1181 * @param $handles Array List of FileBackendStoreOpHandle objects
1182 * @return Array Map of Status objects
1183 * @throws MWException
1185 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1186 wfProfileIn( __METHOD__
);
1187 wfProfileIn( __METHOD__
. '-' . $this->name
);
1188 foreach ( $fileOpHandles as $fileOpHandle ) {
1189 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle
) ) {
1190 throw new MWException( "Given a non-FileBackendStoreOpHandle object." );
1191 } elseif ( $fileOpHandle->backend
->getName() !== $this->getName() ) {
1192 throw new MWException( "Given a FileBackendStoreOpHandle for the wrong backend." );
1195 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1196 foreach ( $fileOpHandles as $fileOpHandle ) {
1197 $fileOpHandle->closeResources();
1199 wfProfileOut( __METHOD__
. '-' . $this->name
);
1200 wfProfileOut( __METHOD__
);
1205 * @see FileBackendStore::executeOpHandlesInternal()
1206 * @param array $fileOpHandles
1207 * @throws MWException
1208 * @return Array List of corresponding Status objects
1210 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1211 foreach ( $fileOpHandles as $fileOpHandle ) { // OK if empty
1212 throw new MWException( "This backend supports no asynchronous operations." );
1218 * Strip long HTTP headers from a file operation
1220 * @param $op array Same format as doOperation()
1223 protected function stripInvalidHeadersFromOp( array $op ) {
1224 if ( isset( $op['headers'] ) ) {
1225 foreach ( $op['headers'] as $name => $value ) {
1226 if ( strlen( $name ) > 255 ||
strlen( $value ) > 255 ) {
1227 trigger_error( "Header '$name: $value' is too long." );
1228 unset( $op['headers'][$name] );
1236 * @see FileBackend::preloadCache()
1238 final public function preloadCache( array $paths ) {
1239 $fullConts = array(); // full container names
1240 foreach ( $paths as $path ) {
1241 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1242 $fullConts[] = $fullCont;
1244 // Load from the persistent file and container caches
1245 $this->primeContainerCache( $fullConts );
1246 $this->primeFileCache( $paths );
1250 * @see FileBackend::clearCache()
1252 final public function clearCache( array $paths = null ) {
1253 if ( is_array( $paths ) ) {
1254 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1255 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1257 if ( $paths === null ) {
1258 $this->cheapCache
->clear();
1259 $this->expensiveCache
->clear();
1261 foreach ( $paths as $path ) {
1262 $this->cheapCache
->clear( $path );
1263 $this->expensiveCache
->clear( $path );
1266 $this->doClearCache( $paths );
1270 * Clears any additional stat caches for storage paths
1272 * @see FileBackend::clearCache()
1274 * @param $paths Array Storage paths (optional)
1277 protected function doClearCache( array $paths = null ) {}
1280 * Is this a key/value store where directories are just virtual?
1281 * Virtual directories exists in so much as files exists that are
1282 * prefixed with the directory path followed by a forward slash.
1286 abstract protected function directoriesAreVirtual();
1289 * Check if a container name is valid.
1290 * This checks for for length and illegal characters.
1292 * @param $container string
1295 final protected static function isValidContainerName( $container ) {
1296 // This accounts for Swift and S3 restrictions while leaving room
1297 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1298 // This disallows directory separators or traversal characters.
1299 // Note that matching strings URL encode to the same string;
1300 // in Swift, the length restriction is *after* URL encoding.
1301 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1305 * Splits a storage path into an internal container name,
1306 * an internal relative file name, and a container shard suffix.
1307 * Any shard suffix is already appended to the internal container name.
1308 * This also checks that the storage path is valid and within this backend.
1310 * If the container is sharded but a suffix could not be determined,
1311 * this means that the path can only refer to a directory and can only
1312 * be scanned by looking in all the container shards.
1314 * @param $storagePath string
1315 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1317 final protected function resolveStoragePath( $storagePath ) {
1318 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1319 if ( $backend === $this->name
) { // must be for this backend
1320 $relPath = self
::normalizeContainerPath( $relPath );
1321 if ( $relPath !== null ) {
1322 // Get shard for the normalized path if this container is sharded
1323 $cShard = $this->getContainerShard( $container, $relPath );
1324 // Validate and sanitize the relative path (backend-specific)
1325 $relPath = $this->resolveContainerPath( $container, $relPath );
1326 if ( $relPath !== null ) {
1327 // Prepend any wiki ID prefix to the container name
1328 $container = $this->fullContainerName( $container );
1329 if ( self
::isValidContainerName( $container ) ) {
1330 // Validate and sanitize the container name (backend-specific)
1331 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1332 if ( $container !== null ) {
1333 return array( $container, $relPath, $cShard );
1339 return array( null, null, null );
1343 * Like resolveStoragePath() except null values are returned if
1344 * the container is sharded and the shard could not be determined.
1346 * @see FileBackendStore::resolveStoragePath()
1348 * @param $storagePath string
1349 * @return Array (container, path) or (null, null) if invalid
1351 final protected function resolveStoragePathReal( $storagePath ) {
1352 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1353 if ( $cShard !== null ) {
1354 return array( $container, $relPath );
1356 return array( null, null );
1360 * Get the container name shard suffix for a given path.
1361 * Any empty suffix means the container is not sharded.
1363 * @param $container string Container name
1364 * @param $relPath string Storage path relative to the container
1365 * @return string|null Returns null if shard could not be determined
1367 final protected function getContainerShard( $container, $relPath ) {
1368 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1369 if ( $levels == 1 ||
$levels == 2 ) {
1370 // Hash characters are either base 16 or 36
1371 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1372 // Get a regex that represents the shard portion of paths.
1373 // The concatenation of the captures gives us the shard.
1374 if ( $levels === 1 ) { // 16 or 36 shards per container
1375 $hashDirRegex = '(' . $char . ')';
1376 } else { // 256 or 1296 shards per container
1377 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1378 $hashDirRegex = $char . '/(' . $char . '{2})';
1379 } else { // short hash dir format (e.g. "a/b/c")
1380 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1383 // Allow certain directories to be above the hash dirs so as
1384 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1385 // They must be 2+ chars to avoid any hash directory ambiguity.
1387 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1388 return '.' . implode( '', array_slice( $m, 1 ) );
1390 return null; // failed to match
1392 return ''; // no sharding
1396 * Check if a storage path maps to a single shard.
1397 * Container dirs like "a", where the container shards on "x/xy",
1398 * can reside on several shards. Such paths are tricky to handle.
1400 * @param $storagePath string Storage path
1403 final public function isSingleShardPathInternal( $storagePath ) {
1404 list( $c, $r, $shard ) = $this->resolveStoragePath( $storagePath );
1405 return ( $shard !== null );
1409 * Get the sharding config for a container.
1410 * If greater than 0, then all file storage paths within
1411 * the container are required to be hashed accordingly.
1413 * @param $container string
1414 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
1416 final protected function getContainerHashLevels( $container ) {
1417 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1418 $config = $this->shardViaHashLevels
[$container];
1419 $hashLevels = (int)$config['levels'];
1420 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1421 $hashBase = (int)$config['base'];
1422 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1423 return array( $hashLevels, $hashBase, $config['repeat'] );
1427 return array( 0, 0, false ); // no sharding
1431 * Get a list of full container shard suffixes for a container
1433 * @param $container string
1436 final protected function getContainerSuffixes( $container ) {
1438 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1439 if ( $digits > 0 ) {
1440 $numShards = pow( $base, $digits );
1441 for ( $index = 0; $index < $numShards; $index++
) {
1442 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1449 * Get the full container name, including the wiki ID prefix
1451 * @param $container string
1454 final protected function fullContainerName( $container ) {
1455 if ( $this->wikiId
!= '' ) {
1456 return "{$this->wikiId}-$container";
1463 * Resolve a container name, checking if it's allowed by the backend.
1464 * This is intended for internal use, such as encoding illegal chars.
1465 * Subclasses can override this to be more restrictive.
1467 * @param $container string
1468 * @return string|null
1470 protected function resolveContainerName( $container ) {
1475 * Resolve a relative storage path, checking if it's allowed by the backend.
1476 * This is intended for internal use, such as encoding illegal chars or perhaps
1477 * getting absolute paths (e.g. FS based backends). Note that the relative path
1478 * may be the empty string (e.g. the path is simply to the container).
1480 * @param $container string Container name
1481 * @param $relStoragePath string Storage path relative to the container
1482 * @return string|null Path or null if not valid
1484 protected function resolveContainerPath( $container, $relStoragePath ) {
1485 return $relStoragePath;
1489 * Get the cache key for a container
1491 * @param $container string Resolved container name
1494 private function containerCacheKey( $container ) {
1495 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1499 * Set the cached info for a container
1501 * @param $container string Resolved container name
1502 * @param $val mixed Information to cache
1504 final protected function setContainerCache( $container, $val ) {
1505 $this->memCache
->add( $this->containerCacheKey( $container ), $val, 14*86400 );
1509 * Delete the cached info for a container.
1510 * The cache key is salted for a while to prevent race conditions.
1512 * @param $container string Resolved container name
1514 final protected function deleteContainerCache( $container ) {
1515 if ( !$this->memCache
->set( $this->containerCacheKey( $container ), 'PURGED', 300 ) ) {
1516 trigger_error( "Unable to delete stat cache for container $container." );
1521 * Do a batch lookup from cache for container stats for all containers
1522 * used in a list of container names, storage paths, or FileOp objects.
1523 * This loads the persistent cache values into the process cache.
1525 * @param $items Array
1528 final protected function primeContainerCache( array $items ) {
1529 wfProfileIn( __METHOD__
);
1530 wfProfileIn( __METHOD__
. '-' . $this->name
);
1532 $paths = array(); // list of storage paths
1533 $contNames = array(); // (cache key => resolved container name)
1534 // Get all the paths/containers from the items...
1535 foreach ( $items as $item ) {
1536 if ( $item instanceof FileOp
) {
1537 $paths = array_merge( $paths, $item->storagePathsRead() );
1538 $paths = array_merge( $paths, $item->storagePathsChanged() );
1539 } elseif ( self
::isStoragePath( $item ) ) {
1541 } elseif ( is_string( $item ) ) { // full container name
1542 $contNames[$this->containerCacheKey( $item )] = $item;
1545 // Get all the corresponding cache keys for paths...
1546 foreach ( $paths as $path ) {
1547 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1548 if ( $fullCont !== null ) { // valid path for this backend
1549 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1553 $contInfo = array(); // (resolved container name => cache value)
1554 // Get all cache entries for these container cache keys...
1555 $values = $this->memCache
->getMulti( array_keys( $contNames ) );
1556 foreach ( $values as $cacheKey => $val ) {
1557 $contInfo[$contNames[$cacheKey]] = $val;
1560 // Populate the container process cache for the backend...
1561 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1563 wfProfileOut( __METHOD__
. '-' . $this->name
);
1564 wfProfileOut( __METHOD__
);
1568 * Fill the backend-specific process cache given an array of
1569 * resolved container names and their corresponding cached info.
1570 * Only containers that actually exist should appear in the map.
1572 * @param $containerInfo Array Map of resolved container names to cached info
1575 protected function doPrimeContainerCache( array $containerInfo ) {}
1578 * Get the cache key for a file path
1580 * @param $path string Normalized storage path
1583 private function fileCacheKey( $path ) {
1584 return wfMemcKey( 'backend', $this->getName(), 'file', sha1( $path ) );
1588 * Set the cached stat info for a file path.
1589 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1590 * salting for the case when a file is created at a path were there was none before.
1592 * @param $path string Storage path
1593 * @param $val mixed Information to cache
1595 final protected function setFileCache( $path, $val ) {
1596 $path = FileBackend
::normalizeStoragePath( $path );
1597 if ( $path === null ) {
1598 return; // invalid storage path
1600 $this->memCache
->add( $this->fileCacheKey( $path ), $val, 7*86400 );
1604 * Delete the cached stat info for a file path.
1605 * The cache key is salted for a while to prevent race conditions.
1607 * @param $path string Storage path
1609 final protected function deleteFileCache( $path ) {
1610 $path = FileBackend
::normalizeStoragePath( $path );
1611 if ( $path === null ) {
1612 return; // invalid storage path
1614 if ( !$this->memCache
->set( $this->fileCacheKey( $path ), 'PURGED', 300 ) ) {
1615 trigger_error( "Unable to delete stat cache for file $path." );
1620 * Do a batch lookup from cache for file stats for all paths
1621 * used in a list of storage paths or FileOp objects.
1622 * This loads the persistent cache values into the process cache.
1624 * @param $items Array List of storage paths or FileOps
1627 final protected function primeFileCache( array $items ) {
1628 wfProfileIn( __METHOD__
);
1629 wfProfileIn( __METHOD__
. '-' . $this->name
);
1631 $paths = array(); // list of storage paths
1632 $pathNames = array(); // (cache key => storage path)
1633 // Get all the paths/containers from the items...
1634 foreach ( $items as $item ) {
1635 if ( $item instanceof FileOp
) {
1636 $paths = array_merge( $paths, $item->storagePathsRead() );
1637 $paths = array_merge( $paths, $item->storagePathsChanged() );
1638 } elseif ( self
::isStoragePath( $item ) ) {
1639 $paths[] = FileBackend
::normalizeStoragePath( $item );
1642 // Get rid of any paths that failed normalization...
1643 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1644 // Get all the corresponding cache keys for paths...
1645 foreach ( $paths as $path ) {
1646 list( $cont, $rel, $s ) = $this->resolveStoragePath( $path );
1647 if ( $rel !== null ) { // valid path for this backend
1648 $pathNames[$this->fileCacheKey( $path )] = $path;
1651 // Get all cache entries for these container cache keys...
1652 $values = $this->memCache
->getMulti( array_keys( $pathNames ) );
1653 foreach ( $values as $cacheKey => $val ) {
1654 if ( is_array( $val ) ) {
1655 $path = $pathNames[$cacheKey];
1656 $this->cheapCache
->set( $path, 'stat', $val );
1657 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1658 $this->cheapCache
->set( $path, 'sha1',
1659 array( 'hash' => $val['sha1'], 'latest' => $val['latest'] ) );
1664 wfProfileOut( __METHOD__
. '-' . $this->name
);
1665 wfProfileOut( __METHOD__
);
1669 * Set the 'concurrency' option from a list of operation options
1671 * @param $opts array Map of operation options
1674 final protected function setConcurrencyFlags( array $opts ) {
1675 $opts['concurrency'] = 1; // off
1676 if ( $this->parallelize
=== 'implicit' ) {
1677 if ( !isset( $opts['parallelize'] ) ||
$opts['parallelize'] ) {
1678 $opts['concurrency'] = $this->concurrency
;
1680 } elseif ( $this->parallelize
=== 'explicit' ) {
1681 if ( !empty( $opts['parallelize'] ) ) {
1682 $opts['concurrency'] = $this->concurrency
;
1690 * FileBackendStore helper class for performing asynchronous file operations.
1692 * For example, calling FileBackendStore::createInternal() with the "async"
1693 * param flag may result in a Status that contains this object as a value.
1694 * This class is largely backend-specific and is mostly just "magic" to be
1695 * passed to FileBackendStore::executeOpHandlesInternal().
1697 abstract class FileBackendStoreOpHandle
{
1699 public $params = array(); // params to caller functions
1700 /** @var FileBackendStore */
1703 public $resourcesToClose = array();
1705 public $call; // string; name that identifies the function called
1708 * Close all open file handles
1712 public function closeResources() {
1713 array_map( 'fclose', $this->resourcesToClose
);
1718 * FileBackendStore helper function to handle listings that span container shards.
1719 * Do not use this class from places outside of FileBackendStore.
1721 * @ingroup FileBackend
1723 abstract class FileBackendStoreShardListIterator
implements Iterator
{
1724 /** @var FileBackendStore */
1729 protected $shardSuffixes;
1730 protected $container; // string; full container name
1731 protected $directory; // string; resolved relative path
1733 /** @var Traversable */
1735 protected $curShard = 0; // integer
1736 protected $pos = 0; // integer
1739 protected $multiShardPaths = array(); // (rel path => 1)
1742 * @param $backend FileBackendStore
1743 * @param $container string Full storage container name
1744 * @param $dir string Storage directory relative to container
1745 * @param $suffixes Array List of container shard suffixes
1746 * @param $params Array
1748 public function __construct(
1749 FileBackendStore
$backend, $container, $dir, array $suffixes, array $params
1751 $this->backend
= $backend;
1752 $this->container
= $container;
1753 $this->directory
= $dir;
1754 $this->shardSuffixes
= $suffixes;
1755 $this->params
= $params;
1759 * @see Iterator::key()
1762 public function key() {
1767 * @see Iterator::valid()
1770 public function valid() {
1771 if ( $this->iter
instanceof Iterator
) {
1772 return $this->iter
->valid();
1773 } elseif ( is_array( $this->iter
) ) {
1774 return ( current( $this->iter
) !== false ); // no paths can have this value
1776 return false; // some failure?
1780 * @see Iterator::current()
1781 * @return string|bool String or false
1783 public function current() {
1784 return ( $this->iter
instanceof Iterator
)
1785 ?
$this->iter
->current()
1786 : current( $this->iter
);
1790 * @see Iterator::next()
1793 public function next() {
1795 ( $this->iter
instanceof Iterator
) ?
$this->iter
->next() : next( $this->iter
);
1797 $continue = false; // keep scanning shards?
1798 $this->filterViaNext(); // filter out duplicates
1799 // Find the next non-empty shard if no elements are left
1800 if ( !$this->valid() ) {
1801 $this->nextShardIteratorIfNotValid();
1802 $continue = $this->valid(); // re-filter unless we ran out of shards
1804 } while ( $continue );
1808 * @see Iterator::rewind()
1811 public function rewind() {
1813 $this->curShard
= 0;
1814 $this->setIteratorFromCurrentShard();
1816 $continue = false; // keep scanning shards?
1817 $this->filterViaNext(); // filter out duplicates
1818 // Find the next non-empty shard if no elements are left
1819 if ( !$this->valid() ) {
1820 $this->nextShardIteratorIfNotValid();
1821 $continue = $this->valid(); // re-filter unless we ran out of shards
1823 } while ( $continue );
1827 * Filter out duplicate items by advancing to the next ones
1829 protected function filterViaNext() {
1830 while ( $this->valid() ) {
1831 $rel = $this->iter
->current(); // path relative to given directory
1832 $path = $this->params
['dir'] . "/{$rel}"; // full storage path
1833 if ( $this->backend
->isSingleShardPathInternal( $path ) ) {
1834 break; // path is only on one shard; no issue with duplicates
1835 } elseif ( isset( $this->multiShardPaths
[$rel] ) ) {
1836 // Don't keep listing paths that are on multiple shards
1837 ( $this->iter
instanceof Iterator
) ?
$this->iter
->next() : next( $this->iter
);
1839 $this->multiShardPaths
[$rel] = 1;
1846 * If the list iterator for this container shard is out of items,
1847 * then move on to the next container that has items.
1848 * If there are none, then it advances to the last container.
1850 protected function nextShardIteratorIfNotValid() {
1851 while ( !$this->valid() && ++
$this->curShard
< count( $this->shardSuffixes
) ) {
1852 $this->setIteratorFromCurrentShard();
1857 * Set the list iterator to that of the current container shard
1859 protected function setIteratorFromCurrentShard() {
1860 $this->iter
= $this->listFromShard(
1861 $this->container
. $this->shardSuffixes
[$this->curShard
],
1862 $this->directory
, $this->params
);
1863 // Start loading results so that current() works
1864 if ( $this->iter
) {
1865 ( $this->iter
instanceof Iterator
) ?
$this->iter
->rewind() : reset( $this->iter
);
1870 * Get the list for a given container shard
1872 * @param $container string Resolved container name
1873 * @param $dir string Resolved path relative to container
1874 * @param $params Array
1875 * @return Traversable|Array|null
1877 abstract protected function listFromShard( $container, $dir, array $params );
1881 * Iterator for listing directories
1883 class FileBackendStoreShardDirIterator
extends FileBackendStoreShardListIterator
{
1885 * @see FileBackendStoreShardListIterator::listFromShard()
1886 * @return Array|null|Traversable
1888 protected function listFromShard( $container, $dir, array $params ) {
1889 return $this->backend
->getDirectoryListInternal( $container, $dir, $params );
1894 * Iterator for listing regular files
1896 class FileBackendStoreShardFileIterator
extends FileBackendStoreShardListIterator
{
1898 * @see FileBackendStoreShardListIterator::listFromShard()
1899 * @return Array|null|Traversable
1901 protected function listFromShard( $container, $dir, array $params ) {
1902 return $this->backend
->getFileListInternal( $container, $dir, $params );