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 * - async : Status will be returned immediately if supported.
97 * If the status is OK, then its value field will be
98 * set to a FileBackendStoreOpHandle object.
100 * @param $params Array
103 final public function createInternal( array $params ) {
104 wfProfileIn( __METHOD__
);
105 wfProfileIn( __METHOD__
. '-' . $this->name
);
106 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
107 $status = Status
::newFatal( 'backend-fail-maxsize',
108 $params['dst'], $this->maxFileSizeInternal() );
110 $status = $this->doCreateInternal( $params );
111 $this->clearCache( array( $params['dst'] ) );
112 $this->deleteFileCache( $params['dst'] ); // persistent cache
114 wfProfileOut( __METHOD__
. '-' . $this->name
);
115 wfProfileOut( __METHOD__
);
120 * @see FileBackendStore::createInternal()
122 abstract protected function doCreateInternal( array $params );
125 * Store a file into the backend from a file on disk.
126 * This will overwrite any file that exists at the destination.
127 * Do not call this function from places outside FileBackend and FileOp.
130 * - src : source path on disk
131 * - dst : destination storage path
132 * - disposition : Content-Disposition header value for the destination
133 * - async : Status will be returned immediately if supported.
134 * If the status is OK, then its value field will be
135 * set to a FileBackendStoreOpHandle object.
137 * @param $params Array
140 final public function storeInternal( array $params ) {
141 wfProfileIn( __METHOD__
);
142 wfProfileIn( __METHOD__
. '-' . $this->name
);
143 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
144 $status = Status
::newFatal( 'backend-fail-maxsize',
145 $params['dst'], $this->maxFileSizeInternal() );
147 $status = $this->doStoreInternal( $params );
148 $this->clearCache( array( $params['dst'] ) );
149 $this->deleteFileCache( $params['dst'] ); // persistent cache
151 wfProfileOut( __METHOD__
. '-' . $this->name
);
152 wfProfileOut( __METHOD__
);
157 * @see FileBackendStore::storeInternal()
159 abstract protected function doStoreInternal( array $params );
162 * Copy a file from one storage path to another in the backend.
163 * This will overwrite any file that exists at the destination.
164 * Do not call this function from places outside FileBackend and FileOp.
167 * - src : source storage path
168 * - dst : destination storage path
169 * - ignoreMissingSource : do nothing if the source file does not exist
170 * - disposition : Content-Disposition header value for the destination
171 * - async : Status will be returned immediately if supported.
172 * If the status is OK, then its value field will be
173 * set to a FileBackendStoreOpHandle object.
175 * @param $params Array
178 final public function copyInternal( array $params ) {
179 wfProfileIn( __METHOD__
);
180 wfProfileIn( __METHOD__
. '-' . $this->name
);
181 $status = $this->doCopyInternal( $params );
182 $this->clearCache( array( $params['dst'] ) );
183 $this->deleteFileCache( $params['dst'] ); // persistent cache
184 wfProfileOut( __METHOD__
. '-' . $this->name
);
185 wfProfileOut( __METHOD__
);
190 * @see FileBackendStore::copyInternal()
192 abstract protected function doCopyInternal( array $params );
195 * Delete a file at the storage path.
196 * Do not call this function from places outside FileBackend and FileOp.
199 * - src : source storage path
200 * - ignoreMissingSource : do nothing if the source file does not exist
201 * - async : Status will be returned immediately if supported.
202 * If the status is OK, then its value field will be
203 * set to a FileBackendStoreOpHandle object.
205 * @param $params Array
208 final public function deleteInternal( array $params ) {
209 wfProfileIn( __METHOD__
);
210 wfProfileIn( __METHOD__
. '-' . $this->name
);
211 $status = $this->doDeleteInternal( $params );
212 $this->clearCache( array( $params['src'] ) );
213 $this->deleteFileCache( $params['src'] ); // persistent cache
214 wfProfileOut( __METHOD__
. '-' . $this->name
);
215 wfProfileOut( __METHOD__
);
220 * @see FileBackendStore::deleteInternal()
222 abstract protected function doDeleteInternal( array $params );
225 * Move a file from one storage path to another in the backend.
226 * This will overwrite any file that exists at the destination.
227 * Do not call this function from places outside FileBackend and FileOp.
230 * - src : source storage path
231 * - dst : destination storage path
232 * - ignoreMissingSource : do nothing if the source file does not exist
233 * - disposition : Content-Disposition header value for the destination
234 * - async : Status will be returned immediately if supported.
235 * If the status is OK, then its value field will be
236 * set to a FileBackendStoreOpHandle object.
238 * @param $params Array
241 final public function moveInternal( array $params ) {
242 wfProfileIn( __METHOD__
);
243 wfProfileIn( __METHOD__
. '-' . $this->name
);
244 $status = $this->doMoveInternal( $params );
245 $this->clearCache( array( $params['src'], $params['dst'] ) );
246 $this->deleteFileCache( $params['src'] ); // persistent cache
247 $this->deleteFileCache( $params['dst'] ); // persistent cache
248 wfProfileOut( __METHOD__
. '-' . $this->name
);
249 wfProfileOut( __METHOD__
);
254 * @see FileBackendStore::moveInternal()
257 protected function doMoveInternal( array $params ) {
258 unset( $params['async'] ); // two steps, won't work here :)
259 // Copy source to dest
260 $status = $this->copyInternal( $params );
261 if ( $status->isOK() ) {
262 // Delete source (only fails due to races or medium going down)
263 $status->merge( $this->deleteInternal( array( 'src' => $params['src'] ) ) );
264 $status->setResult( true, $status->value
); // ignore delete() errors
270 * No-op file operation that does nothing.
271 * Do not call this function from places outside FileBackend and FileOp.
273 * @param $params Array
276 final public function nullInternal( array $params ) {
277 return Status
::newGood();
281 * @see FileBackend::concatenate()
284 final public function concatenate( array $params ) {
285 wfProfileIn( __METHOD__
);
286 wfProfileIn( __METHOD__
. '-' . $this->name
);
287 $status = Status
::newGood();
289 // Try to lock the source files for the scope of this function
290 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager
::LOCK_UW
, $status );
291 if ( $status->isOK() ) {
292 // Actually do the file concatenation...
293 $start_time = microtime( true );
294 $status->merge( $this->doConcatenate( $params ) );
295 $sec = microtime( true ) - $start_time;
296 if ( !$status->isOK() ) {
297 wfDebugLog( 'FileOperation', get_class( $this ) . " failed to concatenate " .
298 count( $params['srcs'] ) . " file(s) [$sec sec]" );
302 wfProfileOut( __METHOD__
. '-' . $this->name
);
303 wfProfileOut( __METHOD__
);
308 * @see FileBackendStore::concatenate()
311 protected function doConcatenate( array $params ) {
312 $status = Status
::newGood();
313 $tmpPath = $params['dst']; // convenience
314 unset( $params['latest'] ); // sanity
316 // Check that the specified temp file is valid...
317 wfSuppressWarnings();
318 $ok = ( is_file( $tmpPath ) && filesize( $tmpPath ) == 0 );
320 if ( !$ok ) { // not present or not empty
321 $status->fatal( 'backend-fail-opentemp', $tmpPath );
325 // Get local FS versions of the chunks needed for the concatenation...
326 $fsFiles = $this->getLocalReferenceMulti( $params );
327 foreach ( $fsFiles as $path => &$fsFile ) {
328 if ( !$fsFile ) { // chunk failed to download?
329 $fsFile = $this->getLocalReference( array( 'src' => $path ) );
330 if ( !$fsFile ) { // retry failed?
331 $status->fatal( 'backend-fail-read', $path );
336 unset( $fsFile ); // unset reference so we can reuse $fsFile
338 // Get a handle for the destination temp file
339 $tmpHandle = fopen( $tmpPath, 'ab' );
340 if ( $tmpHandle === false ) {
341 $status->fatal( 'backend-fail-opentemp', $tmpPath );
345 // Build up the temp file using the source chunks (in order)...
346 foreach ( $fsFiles as $virtualSource => $fsFile ) {
347 // Get a handle to the local FS version
348 $sourceHandle = fopen( $fsFile->getPath(), 'rb' );
349 if ( $sourceHandle === false ) {
350 fclose( $tmpHandle );
351 $status->fatal( 'backend-fail-read', $virtualSource );
354 // Append chunk to file (pass chunk size to avoid magic quotes)
355 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
356 fclose( $sourceHandle );
357 fclose( $tmpHandle );
358 $status->fatal( 'backend-fail-writetemp', $tmpPath );
361 fclose( $sourceHandle );
363 if ( !fclose( $tmpHandle ) ) {
364 $status->fatal( 'backend-fail-closetemp', $tmpPath );
368 clearstatcache(); // temp file changed
374 * @see FileBackend::doPrepare()
377 final protected function doPrepare( array $params ) {
378 wfProfileIn( __METHOD__
);
379 wfProfileIn( __METHOD__
. '-' . $this->name
);
381 $status = Status
::newGood();
382 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
383 if ( $dir === null ) {
384 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
385 wfProfileOut( __METHOD__
. '-' . $this->name
);
386 wfProfileOut( __METHOD__
);
387 return $status; // invalid storage path
390 if ( $shard !== null ) { // confined to a single container/shard
391 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
392 } else { // directory is on several shards
393 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
394 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
395 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
396 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
400 wfProfileOut( __METHOD__
. '-' . $this->name
);
401 wfProfileOut( __METHOD__
);
406 * @see FileBackendStore::doPrepare()
409 protected function doPrepareInternal( $container, $dir, array $params ) {
410 return Status
::newGood();
414 * @see FileBackend::doSecure()
417 final protected function doSecure( array $params ) {
418 wfProfileIn( __METHOD__
);
419 wfProfileIn( __METHOD__
. '-' . $this->name
);
420 $status = Status
::newGood();
422 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
423 if ( $dir === null ) {
424 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
425 wfProfileOut( __METHOD__
. '-' . $this->name
);
426 wfProfileOut( __METHOD__
);
427 return $status; // invalid storage path
430 if ( $shard !== null ) { // confined to a single container/shard
431 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
432 } else { // directory is on several shards
433 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
434 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
435 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
436 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
440 wfProfileOut( __METHOD__
. '-' . $this->name
);
441 wfProfileOut( __METHOD__
);
446 * @see FileBackendStore::doSecure()
449 protected function doSecureInternal( $container, $dir, array $params ) {
450 return Status
::newGood();
454 * @see FileBackend::doPublish()
457 final protected function doPublish( array $params ) {
458 wfProfileIn( __METHOD__
);
459 wfProfileIn( __METHOD__
. '-' . $this->name
);
460 $status = Status
::newGood();
462 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
463 if ( $dir === null ) {
464 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
465 wfProfileOut( __METHOD__
. '-' . $this->name
);
466 wfProfileOut( __METHOD__
);
467 return $status; // invalid storage path
470 if ( $shard !== null ) { // confined to a single container/shard
471 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
472 } else { // directory is on several shards
473 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
474 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
475 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
476 $status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
480 wfProfileOut( __METHOD__
. '-' . $this->name
);
481 wfProfileOut( __METHOD__
);
486 * @see FileBackendStore::doPublish()
489 protected function doPublishInternal( $container, $dir, array $params ) {
490 return Status
::newGood();
494 * @see FileBackend::doClean()
497 final protected function doClean( array $params ) {
498 wfProfileIn( __METHOD__
);
499 wfProfileIn( __METHOD__
. '-' . $this->name
);
500 $status = Status
::newGood();
502 // Recursive: first delete all empty subdirs recursively
503 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
504 $subDirsRel = $this->getTopDirectoryList( array( 'dir' => $params['dir'] ) );
505 if ( $subDirsRel !== null ) { // no errors
506 foreach ( $subDirsRel as $subDirRel ) {
507 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
508 $status->merge( $this->doClean( array( 'dir' => $subDir ) +
$params ) );
510 unset( $subDirsRel ); // free directory for rmdir() on Windows (for FS backends)
514 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
515 if ( $dir === null ) {
516 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
517 wfProfileOut( __METHOD__
. '-' . $this->name
);
518 wfProfileOut( __METHOD__
);
519 return $status; // invalid storage path
522 // Attempt to lock this directory...
523 $filesLockEx = array( $params['dir'] );
524 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
525 if ( !$status->isOK() ) {
526 wfProfileOut( __METHOD__
. '-' . $this->name
);
527 wfProfileOut( __METHOD__
);
528 return $status; // abort
531 if ( $shard !== null ) { // confined to a single container/shard
532 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
533 $this->deleteContainerCache( $fullCont ); // purge cache
534 } else { // directory is on several shards
535 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
536 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
537 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
538 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
539 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
543 wfProfileOut( __METHOD__
. '-' . $this->name
);
544 wfProfileOut( __METHOD__
);
549 * @see FileBackendStore::doClean()
552 protected function doCleanInternal( $container, $dir, array $params ) {
553 return Status
::newGood();
557 * @see FileBackend::fileExists()
560 final public function fileExists( 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 === null ) ?
null : (bool)$stat; // null => failure
570 * @see FileBackend::getFileTimestamp()
573 final public function getFileTimestamp( array $params ) {
574 wfProfileIn( __METHOD__
);
575 wfProfileIn( __METHOD__
. '-' . $this->name
);
576 $stat = $this->getFileStat( $params );
577 wfProfileOut( __METHOD__
. '-' . $this->name
);
578 wfProfileOut( __METHOD__
);
579 return $stat ?
$stat['mtime'] : false;
583 * @see FileBackend::getFileSize()
586 final public function getFileSize( array $params ) {
587 wfProfileIn( __METHOD__
);
588 wfProfileIn( __METHOD__
. '-' . $this->name
);
589 $stat = $this->getFileStat( $params );
590 wfProfileOut( __METHOD__
. '-' . $this->name
);
591 wfProfileOut( __METHOD__
);
592 return $stat ?
$stat['size'] : false;
596 * @see FileBackend::getFileStat()
599 final public function getFileStat( array $params ) {
600 $path = self
::normalizeStoragePath( $params['src'] );
601 if ( $path === null ) {
602 return false; // invalid storage path
604 wfProfileIn( __METHOD__
);
605 wfProfileIn( __METHOD__
. '-' . $this->name
);
606 $latest = !empty( $params['latest'] ); // use latest data?
607 if ( !$this->cheapCache
->has( $path, 'stat', self
::CACHE_TTL
) ) {
608 $this->primeFileCache( array( $path ) ); // check persistent cache
610 if ( $this->cheapCache
->has( $path, 'stat', self
::CACHE_TTL
) ) {
611 $stat = $this->cheapCache
->get( $path, 'stat' );
612 // If we want the latest data, check that this cached
613 // value was in fact fetched with the latest available data
614 // (the process cache is ignored if it contains a negative).
615 if ( !$latest ||
( is_array( $stat ) && $stat['latest'] ) ) {
616 wfProfileOut( __METHOD__
. '-' . $this->name
);
617 wfProfileOut( __METHOD__
);
621 wfProfileIn( __METHOD__
. '-miss' );
622 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
623 $stat = $this->doGetFileStat( $params );
624 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
625 wfProfileOut( __METHOD__
. '-miss' );
626 if ( is_array( $stat ) ) { // file exists
627 $stat['latest'] = $latest;
628 $this->cheapCache
->set( $path, 'stat', $stat );
629 $this->setFileCache( $path, $stat ); // update persistent cache
630 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
631 $this->cheapCache
->set( $path, 'sha1',
632 array( 'hash' => $stat['sha1'], 'latest' => $latest ) );
634 } elseif ( $stat === false ) { // file does not exist
635 $this->cheapCache
->set( $path, 'stat', false );
636 wfDebug( __METHOD__
. ": File $path does not exist.\n" );
637 } else { // an error occurred
638 wfDebug( __METHOD__
. ": Could not stat file $path.\n" );
640 wfProfileOut( __METHOD__
. '-' . $this->name
);
641 wfProfileOut( __METHOD__
);
646 * @see FileBackendStore::getFileStat()
648 abstract protected function doGetFileStat( array $params );
651 * @see FileBackend::getFileContentsMulti()
654 public function getFileContentsMulti( array $params ) {
655 wfProfileIn( __METHOD__
);
656 wfProfileIn( __METHOD__
. '-' . $this->name
);
658 $params = $this->setConcurrencyFlags( $params );
659 $contents = $this->doGetFileContentsMulti( $params );
661 wfProfileOut( __METHOD__
. '-' . $this->name
);
662 wfProfileOut( __METHOD__
);
667 * @see FileBackendStore::getFileContentsMulti()
670 protected function doGetFileContentsMulti( array $params ) {
672 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
673 wfSuppressWarnings();
674 $contents[$path] = $fsFile ?
file_get_contents( $fsFile->getPath() ) : false;
681 * @see FileBackend::getFileSha1Base36()
682 * @return bool|string
684 final public function getFileSha1Base36( array $params ) {
685 $path = self
::normalizeStoragePath( $params['src'] );
686 if ( $path === null ) {
687 return false; // invalid storage path
689 wfProfileIn( __METHOD__
);
690 wfProfileIn( __METHOD__
. '-' . $this->name
);
691 $latest = !empty( $params['latest'] ); // use latest data?
692 if ( $this->cheapCache
->has( $path, 'sha1', self
::CACHE_TTL
) ) {
693 $stat = $this->cheapCache
->get( $path, 'sha1' );
694 // If we want the latest data, check that this cached
695 // value was in fact fetched with the latest available data.
696 if ( !$latest ||
$stat['latest'] ) {
697 wfProfileOut( __METHOD__
. '-' . $this->name
);
698 wfProfileOut( __METHOD__
);
699 return $stat['hash'];
702 wfProfileIn( __METHOD__
. '-miss' );
703 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
704 $hash = $this->doGetFileSha1Base36( $params );
705 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
706 wfProfileOut( __METHOD__
. '-miss' );
707 if ( $hash ) { // don't cache negatives
708 $this->cheapCache
->set( $path, 'sha1',
709 array( 'hash' => $hash, 'latest' => $latest ) );
711 wfProfileOut( __METHOD__
. '-' . $this->name
);
712 wfProfileOut( __METHOD__
);
717 * @see FileBackendStore::getFileSha1Base36()
718 * @return bool|string
720 protected function doGetFileSha1Base36( array $params ) {
721 $fsFile = $this->getLocalReference( $params );
725 return $fsFile->getSha1Base36();
730 * @see FileBackend::getFileProps()
733 final public function getFileProps( array $params ) {
734 wfProfileIn( __METHOD__
);
735 wfProfileIn( __METHOD__
. '-' . $this->name
);
736 $fsFile = $this->getLocalReference( $params );
737 $props = $fsFile ?
$fsFile->getProps() : FSFile
::placeholderProps();
738 wfProfileOut( __METHOD__
. '-' . $this->name
);
739 wfProfileOut( __METHOD__
);
744 * @see FileBackend::getLocalReferenceMulti()
747 final public function getLocalReferenceMulti( array $params ) {
748 wfProfileIn( __METHOD__
);
749 wfProfileIn( __METHOD__
. '-' . $this->name
);
751 $params = $this->setConcurrencyFlags( $params );
753 $fsFiles = array(); // (path => FSFile)
754 $latest = !empty( $params['latest'] ); // use latest data?
755 // Reuse any files already in process cache...
756 foreach ( $params['srcs'] as $src ) {
757 $path = self
::normalizeStoragePath( $src );
758 if ( $path === null ) {
759 $fsFiles[$src] = null; // invalid storage path
760 } elseif ( $this->expensiveCache
->has( $path, 'localRef' ) ) {
761 $val = $this->expensiveCache
->get( $path, 'localRef' );
762 // If we want the latest data, check that this cached
763 // value was in fact fetched with the latest available data.
764 if ( !$latest ||
$val['latest'] ) {
765 $fsFiles[$src] = $val['object'];
769 // Fetch local references of any remaning files...
770 $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
771 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
772 $fsFiles[$path] = $fsFile;
773 if ( $fsFile ) { // update the process cache...
774 $this->expensiveCache
->set( $path, 'localRef',
775 array( 'object' => $fsFile, 'latest' => $latest ) );
779 wfProfileOut( __METHOD__
. '-' . $this->name
);
780 wfProfileOut( __METHOD__
);
785 * @see FileBackendStore::getLocalReferenceMulti()
788 protected function doGetLocalReferenceMulti( array $params ) {
789 return $this->doGetLocalCopyMulti( $params );
793 * @see FileBackend::getLocalCopyMulti()
796 final public function getLocalCopyMulti( array $params ) {
797 wfProfileIn( __METHOD__
);
798 wfProfileIn( __METHOD__
. '-' . $this->name
);
800 $params = $this->setConcurrencyFlags( $params );
801 $tmpFiles = $this->doGetLocalCopyMulti( $params );
803 wfProfileOut( __METHOD__
. '-' . $this->name
);
804 wfProfileOut( __METHOD__
);
809 * @see FileBackendStore::getLocalCopyMulti()
812 abstract protected function doGetLocalCopyMulti( array $params );
815 * @see FileBackend::getFileHttpUrl()
816 * @return string|null
818 public function getFileHttpUrl( array $params ) {
819 return null; // not supported
823 * @see FileBackend::streamFile()
826 final public function streamFile( array $params ) {
827 wfProfileIn( __METHOD__
);
828 wfProfileIn( __METHOD__
. '-' . $this->name
);
829 $status = Status
::newGood();
831 $info = $this->getFileStat( $params );
832 if ( !$info ) { // let StreamFile handle the 404
833 $status->fatal( 'backend-fail-notexists', $params['src'] );
836 // Set output buffer and HTTP headers for stream
837 $extraHeaders = isset( $params['headers'] ) ?
$params['headers'] : array();
838 $res = StreamFile
::prepareForStream( $params['src'], $info, $extraHeaders );
839 if ( $res == StreamFile
::NOT_MODIFIED
) {
840 // do nothing; client cache is up to date
841 } elseif ( $res == StreamFile
::READY_STREAM
) {
842 wfProfileIn( __METHOD__
. '-send' );
843 wfProfileIn( __METHOD__
. '-send-' . $this->name
);
844 $status = $this->doStreamFile( $params );
845 wfProfileOut( __METHOD__
. '-send-' . $this->name
);
846 wfProfileOut( __METHOD__
. '-send' );
847 if ( !$status->isOK() ) {
848 // Per bug 41113, nasty things can happen if bad cache entries get
849 // stuck in cache. It's also possible that this error can come up
850 // with simple race conditions. Clear out the stat cache to be safe.
851 $this->clearCache( array( $params['src'] ) );
852 $this->deleteFileCache( $params['src'] );
853 trigger_error( "Bad stat cache or race condition for file {$params['src']}." );
856 $status->fatal( 'backend-fail-stream', $params['src'] );
859 wfProfileOut( __METHOD__
. '-' . $this->name
);
860 wfProfileOut( __METHOD__
);
865 * @see FileBackendStore::streamFile()
868 protected function doStreamFile( array $params ) {
869 $status = Status
::newGood();
871 $fsFile = $this->getLocalReference( $params );
873 $status->fatal( 'backend-fail-stream', $params['src'] );
874 } elseif ( !readfile( $fsFile->getPath() ) ) {
875 $status->fatal( 'backend-fail-stream', $params['src'] );
882 * @see FileBackend::directoryExists()
885 final public function directoryExists( array $params ) {
886 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
887 if ( $dir === null ) {
888 return false; // invalid storage path
890 if ( $shard !== null ) { // confined to a single container/shard
891 return $this->doDirectoryExists( $fullCont, $dir, $params );
892 } else { // directory is on several shards
893 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
894 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
895 $res = false; // response
896 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
897 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
901 } elseif ( $exists === null ) { // error?
902 $res = null; // if we don't find anything, it is indeterminate
910 * @see FileBackendStore::directoryExists()
912 * @param $container string Resolved container name
913 * @param $dir string Resolved path relative to container
914 * @param $params Array
917 abstract protected function doDirectoryExists( $container, $dir, array $params );
920 * @see FileBackend::getDirectoryList()
921 * @return Traversable|Array|null Returns null on failure
923 final public function getDirectoryList( array $params ) {
924 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
925 if ( $dir === null ) { // invalid storage path
928 if ( $shard !== null ) {
929 // File listing is confined to a single container/shard
930 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
932 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
933 // File listing spans multiple containers/shards
934 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
935 return new FileBackendStoreShardDirIterator( $this,
936 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
941 * Do not call this function from places outside FileBackend
943 * @see FileBackendStore::getDirectoryList()
945 * @param $container string Resolved container name
946 * @param $dir string Resolved path relative to container
947 * @param $params Array
948 * @return Traversable|Array|null Returns null on failure
950 abstract public function getDirectoryListInternal( $container, $dir, array $params );
953 * @see FileBackend::getFileList()
954 * @return Traversable|Array|null Returns null on failure
956 final public function getFileList( array $params ) {
957 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
958 if ( $dir === null ) { // invalid storage path
961 if ( $shard !== null ) {
962 // File listing is confined to a single container/shard
963 return $this->getFileListInternal( $fullCont, $dir, $params );
965 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
966 // File listing spans multiple containers/shards
967 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
968 return new FileBackendStoreShardFileIterator( $this,
969 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
974 * Do not call this function from places outside FileBackend
976 * @see FileBackendStore::getFileList()
978 * @param $container string Resolved container name
979 * @param $dir string Resolved path relative to container
980 * @param $params Array
981 * @return Traversable|Array|null Returns null on failure
983 abstract public function getFileListInternal( $container, $dir, array $params );
986 * Return a list of FileOp objects from a list of operations.
987 * Do not call this function from places outside FileBackend.
989 * The result must have the same number of items as the input.
990 * An exception is thrown if an unsupported operation is requested.
992 * @param $ops Array Same format as doOperations()
993 * @return Array List of FileOp objects
994 * @throws MWException
996 final public function getOperationsInternal( array $ops ) {
997 $supportedOps = array(
998 'store' => 'StoreFileOp',
999 'copy' => 'CopyFileOp',
1000 'move' => 'MoveFileOp',
1001 'delete' => 'DeleteFileOp',
1002 'create' => 'CreateFileOp',
1003 'null' => 'NullFileOp'
1006 $performOps = array(); // array of FileOp objects
1007 // Build up ordered array of FileOps...
1008 foreach ( $ops as $operation ) {
1009 $opName = $operation['op'];
1010 if ( isset( $supportedOps[$opName] ) ) {
1011 $class = $supportedOps[$opName];
1012 // Get params for this operation
1013 $params = $operation;
1014 // Append the FileOp class
1015 $performOps[] = new $class( $this, $params );
1017 throw new MWException( "Operation '$opName' is not supported." );
1025 * Get a list of storage paths to lock for a list of operations
1026 * Returns an array with 'sh' (shared) and 'ex' (exclusive) keys,
1027 * each corresponding to a list of storage paths to be locked.
1028 * All returned paths are normalized.
1030 * @param $performOps Array List of FileOp objects
1031 * @return Array ('sh' => list of paths, 'ex' => list of paths)
1033 final public function getPathsToLockForOpsInternal( array $performOps ) {
1034 // Build up a list of files to lock...
1035 $paths = array( 'sh' => array(), 'ex' => array() );
1036 foreach ( $performOps as $fileOp ) {
1037 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1038 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1040 // Optimization: if doing an EX lock anyway, don't also set an SH one
1041 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1042 // Get a shared lock on the parent directory of each path changed
1043 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1049 * @see FileBackend::getScopedLocksForOps()
1052 public function getScopedLocksForOps( array $ops, Status
$status ) {
1053 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1055 $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status ),
1056 $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status )
1061 * @see FileBackend::doOperationsInternal()
1064 final protected function doOperationsInternal( array $ops, array $opts ) {
1065 wfProfileIn( __METHOD__
);
1066 wfProfileIn( __METHOD__
. '-' . $this->name
);
1067 $status = Status
::newGood();
1069 // Build up a list of FileOps...
1070 $performOps = $this->getOperationsInternal( $ops );
1072 // Acquire any locks as needed...
1073 if ( empty( $opts['nonLocking'] ) ) {
1074 // Build up a list of files to lock...
1075 $paths = $this->getPathsToLockForOpsInternal( $performOps );
1076 // Try to lock those files for the scope of this function...
1077 $scopeLockS = $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status );
1078 $scopeLockE = $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status );
1079 if ( !$status->isOK() ) {
1080 wfProfileOut( __METHOD__
. '-' . $this->name
);
1081 wfProfileOut( __METHOD__
);
1082 return $status; // abort
1086 // Clear any file cache entries (after locks acquired)
1087 if ( empty( $opts['preserveCache'] ) ) {
1088 $this->clearCache();
1091 // Load from the persistent file and container caches
1092 $this->primeFileCache( $performOps );
1093 $this->primeContainerCache( $performOps );
1095 // Actually attempt the operation batch...
1096 $opts = $this->setConcurrencyFlags( $opts );
1097 $subStatus = FileOpBatch
::attempt( $performOps, $opts, $this->fileJournal
);
1099 // Merge errors into status fields
1100 $status->merge( $subStatus );
1101 $status->success
= $subStatus->success
; // not done in merge()
1103 wfProfileOut( __METHOD__
. '-' . $this->name
);
1104 wfProfileOut( __METHOD__
);
1109 * @see FileBackend::doQuickOperationsInternal()
1111 * @throws MWException
1113 final protected function doQuickOperationsInternal( array $ops ) {
1114 wfProfileIn( __METHOD__
);
1115 wfProfileIn( __METHOD__
. '-' . $this->name
);
1116 $status = Status
::newGood();
1118 // Clear any file cache entries
1119 $this->clearCache();
1121 $supportedOps = array( 'create', 'store', 'copy', 'move', 'delete', 'null' );
1122 $async = ( $this->parallelize
=== 'implicit' );
1123 $maxConcurrency = $this->concurrency
; // throttle
1125 $statuses = array(); // array of (index => Status)
1126 $fileOpHandles = array(); // list of (index => handle) arrays
1127 $curFileOpHandles = array(); // current handle batch
1128 // Perform the sync-only ops and build up op handles for the async ops...
1129 foreach ( $ops as $index => $params ) {
1130 if ( !in_array( $params['op'], $supportedOps ) ) {
1131 wfProfileOut( __METHOD__
. '-' . $this->name
);
1132 wfProfileOut( __METHOD__
);
1133 throw new MWException( "Operation '{$params['op']}' is not supported." );
1135 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1136 $subStatus = $this->$method( array( 'async' => $async ) +
$params );
1137 if ( $subStatus->value
instanceof FileBackendStoreOpHandle
) { // async
1138 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1139 $fileOpHandles[] = $curFileOpHandles; // push this batch
1140 $curFileOpHandles = array();
1142 $curFileOpHandles[$index] = $subStatus->value
; // keep index
1143 } else { // error or completed
1144 $statuses[$index] = $subStatus; // keep index
1147 if ( count( $curFileOpHandles ) ) {
1148 $fileOpHandles[] = $curFileOpHandles; // last batch
1150 // Do all the async ops that can be done concurrently...
1151 foreach ( $fileOpHandles as $fileHandleBatch ) {
1152 $statuses = $statuses +
$this->executeOpHandlesInternal( $fileHandleBatch );
1154 // Marshall and merge all the responses...
1155 foreach ( $statuses as $index => $subStatus ) {
1156 $status->merge( $subStatus );
1157 if ( $subStatus->isOK() ) {
1158 $status->success
[$index] = true;
1159 ++
$status->successCount
;
1161 $status->success
[$index] = false;
1162 ++
$status->failCount
;
1166 wfProfileOut( __METHOD__
. '-' . $this->name
);
1167 wfProfileOut( __METHOD__
);
1172 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1173 * The resulting Status object fields will correspond
1174 * to the order in which the handles where given.
1176 * @param $handles Array List of FileBackendStoreOpHandle objects
1177 * @return Array Map of Status objects
1178 * @throws MWException
1180 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1181 wfProfileIn( __METHOD__
);
1182 wfProfileIn( __METHOD__
. '-' . $this->name
);
1183 foreach ( $fileOpHandles as $fileOpHandle ) {
1184 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle
) ) {
1185 throw new MWException( "Given a non-FileBackendStoreOpHandle object." );
1186 } elseif ( $fileOpHandle->backend
->getName() !== $this->getName() ) {
1187 throw new MWException( "Given a FileBackendStoreOpHandle for the wrong backend." );
1190 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1191 foreach ( $fileOpHandles as $fileOpHandle ) {
1192 $fileOpHandle->closeResources();
1194 wfProfileOut( __METHOD__
. '-' . $this->name
);
1195 wfProfileOut( __METHOD__
);
1200 * @see FileBackendStore::executeOpHandlesInternal()
1201 * @param array $fileOpHandles
1202 * @throws MWException
1203 * @return Array List of corresponding Status objects
1205 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1206 foreach ( $fileOpHandles as $fileOpHandle ) { // OK if empty
1207 throw new MWException( "This backend supports no asynchronous operations." );
1213 * @see FileBackend::preloadCache()
1215 final public function preloadCache( array $paths ) {
1216 $fullConts = array(); // full container names
1217 foreach ( $paths as $path ) {
1218 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1219 $fullConts[] = $fullCont;
1221 // Load from the persistent file and container caches
1222 $this->primeContainerCache( $fullConts );
1223 $this->primeFileCache( $paths );
1227 * @see FileBackend::clearCache()
1229 final public function clearCache( array $paths = null ) {
1230 if ( is_array( $paths ) ) {
1231 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1232 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1234 if ( $paths === null ) {
1235 $this->cheapCache
->clear();
1236 $this->expensiveCache
->clear();
1238 foreach ( $paths as $path ) {
1239 $this->cheapCache
->clear( $path );
1240 $this->expensiveCache
->clear( $path );
1243 $this->doClearCache( $paths );
1247 * Clears any additional stat caches for storage paths
1249 * @see FileBackend::clearCache()
1251 * @param $paths Array Storage paths (optional)
1254 protected function doClearCache( array $paths = null ) {}
1257 * Is this a key/value store where directories are just virtual?
1258 * Virtual directories exists in so much as files exists that are
1259 * prefixed with the directory path followed by a forward slash.
1263 abstract protected function directoriesAreVirtual();
1266 * Check if a container name is valid.
1267 * This checks for for length and illegal characters.
1269 * @param $container string
1272 final protected static function isValidContainerName( $container ) {
1273 // This accounts for Swift and S3 restrictions while leaving room
1274 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1275 // This disallows directory separators or traversal characters.
1276 // Note that matching strings URL encode to the same string;
1277 // in Swift, the length restriction is *after* URL encoding.
1278 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1282 * Splits a storage path into an internal container name,
1283 * an internal relative file name, and a container shard suffix.
1284 * Any shard suffix is already appended to the internal container name.
1285 * This also checks that the storage path is valid and within this backend.
1287 * If the container is sharded but a suffix could not be determined,
1288 * this means that the path can only refer to a directory and can only
1289 * be scanned by looking in all the container shards.
1291 * @param $storagePath string
1292 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1294 final protected function resolveStoragePath( $storagePath ) {
1295 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1296 if ( $backend === $this->name
) { // must be for this backend
1297 $relPath = self
::normalizeContainerPath( $relPath );
1298 if ( $relPath !== null ) {
1299 // Get shard for the normalized path if this container is sharded
1300 $cShard = $this->getContainerShard( $container, $relPath );
1301 // Validate and sanitize the relative path (backend-specific)
1302 $relPath = $this->resolveContainerPath( $container, $relPath );
1303 if ( $relPath !== null ) {
1304 // Prepend any wiki ID prefix to the container name
1305 $container = $this->fullContainerName( $container );
1306 if ( self
::isValidContainerName( $container ) ) {
1307 // Validate and sanitize the container name (backend-specific)
1308 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1309 if ( $container !== null ) {
1310 return array( $container, $relPath, $cShard );
1316 return array( null, null, null );
1320 * Like resolveStoragePath() except null values are returned if
1321 * the container is sharded and the shard could not be determined.
1323 * @see FileBackendStore::resolveStoragePath()
1325 * @param $storagePath string
1326 * @return Array (container, path) or (null, null) if invalid
1328 final protected function resolveStoragePathReal( $storagePath ) {
1329 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1330 if ( $cShard !== null ) {
1331 return array( $container, $relPath );
1333 return array( null, null );
1337 * Get the container name shard suffix for a given path.
1338 * Any empty suffix means the container is not sharded.
1340 * @param $container string Container name
1341 * @param $relPath string Storage path relative to the container
1342 * @return string|null Returns null if shard could not be determined
1344 final protected function getContainerShard( $container, $relPath ) {
1345 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1346 if ( $levels == 1 ||
$levels == 2 ) {
1347 // Hash characters are either base 16 or 36
1348 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1349 // Get a regex that represents the shard portion of paths.
1350 // The concatenation of the captures gives us the shard.
1351 if ( $levels === 1 ) { // 16 or 36 shards per container
1352 $hashDirRegex = '(' . $char . ')';
1353 } else { // 256 or 1296 shards per container
1354 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1355 $hashDirRegex = $char . '/(' . $char . '{2})';
1356 } else { // short hash dir format (e.g. "a/b/c")
1357 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1360 // Allow certain directories to be above the hash dirs so as
1361 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1362 // They must be 2+ chars to avoid any hash directory ambiguity.
1364 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1365 return '.' . implode( '', array_slice( $m, 1 ) );
1367 return null; // failed to match
1369 return ''; // no sharding
1373 * Check if a storage path maps to a single shard.
1374 * Container dirs like "a", where the container shards on "x/xy",
1375 * can reside on several shards. Such paths are tricky to handle.
1377 * @param $storagePath string Storage path
1380 final public function isSingleShardPathInternal( $storagePath ) {
1381 list( $c, $r, $shard ) = $this->resolveStoragePath( $storagePath );
1382 return ( $shard !== null );
1386 * Get the sharding config for a container.
1387 * If greater than 0, then all file storage paths within
1388 * the container are required to be hashed accordingly.
1390 * @param $container string
1391 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
1393 final protected function getContainerHashLevels( $container ) {
1394 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1395 $config = $this->shardViaHashLevels
[$container];
1396 $hashLevels = (int)$config['levels'];
1397 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1398 $hashBase = (int)$config['base'];
1399 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1400 return array( $hashLevels, $hashBase, $config['repeat'] );
1404 return array( 0, 0, false ); // no sharding
1408 * Get a list of full container shard suffixes for a container
1410 * @param $container string
1413 final protected function getContainerSuffixes( $container ) {
1415 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1416 if ( $digits > 0 ) {
1417 $numShards = pow( $base, $digits );
1418 for ( $index = 0; $index < $numShards; $index++
) {
1419 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1426 * Get the full container name, including the wiki ID prefix
1428 * @param $container string
1431 final protected function fullContainerName( $container ) {
1432 if ( $this->wikiId
!= '' ) {
1433 return "{$this->wikiId}-$container";
1440 * Resolve a container name, checking if it's allowed by the backend.
1441 * This is intended for internal use, such as encoding illegal chars.
1442 * Subclasses can override this to be more restrictive.
1444 * @param $container string
1445 * @return string|null
1447 protected function resolveContainerName( $container ) {
1452 * Resolve a relative storage path, checking if it's allowed by the backend.
1453 * This is intended for internal use, such as encoding illegal chars or perhaps
1454 * getting absolute paths (e.g. FS based backends). Note that the relative path
1455 * may be the empty string (e.g. the path is simply to the container).
1457 * @param $container string Container name
1458 * @param $relStoragePath string Storage path relative to the container
1459 * @return string|null Path or null if not valid
1461 protected function resolveContainerPath( $container, $relStoragePath ) {
1462 return $relStoragePath;
1466 * Get the cache key for a container
1468 * @param $container string Resolved container name
1471 private function containerCacheKey( $container ) {
1472 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1476 * Set the cached info for a container
1478 * @param $container string Resolved container name
1479 * @param $val mixed Information to cache
1481 final protected function setContainerCache( $container, $val ) {
1482 $this->memCache
->add( $this->containerCacheKey( $container ), $val, 14*86400 );
1486 * Delete the cached info for a container.
1487 * The cache key is salted for a while to prevent race conditions.
1489 * @param $container string Resolved container name
1491 final protected function deleteContainerCache( $container ) {
1492 if ( !$this->memCache
->set( $this->containerCacheKey( $container ), 'PURGED', 300 ) ) {
1493 trigger_error( "Unable to delete stat cache for container $container." );
1498 * Do a batch lookup from cache for container stats for all containers
1499 * used in a list of container names, storage paths, or FileOp objects.
1500 * This loads the persistent cache values into the process cache.
1502 * @param $items Array
1505 final protected function primeContainerCache( array $items ) {
1506 wfProfileIn( __METHOD__
);
1507 wfProfileIn( __METHOD__
. '-' . $this->name
);
1509 $paths = array(); // list of storage paths
1510 $contNames = array(); // (cache key => resolved container name)
1511 // Get all the paths/containers from the items...
1512 foreach ( $items as $item ) {
1513 if ( $item instanceof FileOp
) {
1514 $paths = array_merge( $paths, $item->storagePathsRead() );
1515 $paths = array_merge( $paths, $item->storagePathsChanged() );
1516 } elseif ( self
::isStoragePath( $item ) ) {
1518 } elseif ( is_string( $item ) ) { // full container name
1519 $contNames[$this->containerCacheKey( $item )] = $item;
1522 // Get all the corresponding cache keys for paths...
1523 foreach ( $paths as $path ) {
1524 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1525 if ( $fullCont !== null ) { // valid path for this backend
1526 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1530 $contInfo = array(); // (resolved container name => cache value)
1531 // Get all cache entries for these container cache keys...
1532 $values = $this->memCache
->getMulti( array_keys( $contNames ) );
1533 foreach ( $values as $cacheKey => $val ) {
1534 $contInfo[$contNames[$cacheKey]] = $val;
1537 // Populate the container process cache for the backend...
1538 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1540 wfProfileOut( __METHOD__
. '-' . $this->name
);
1541 wfProfileOut( __METHOD__
);
1545 * Fill the backend-specific process cache given an array of
1546 * resolved container names and their corresponding cached info.
1547 * Only containers that actually exist should appear in the map.
1549 * @param $containerInfo Array Map of resolved container names to cached info
1552 protected function doPrimeContainerCache( array $containerInfo ) {}
1555 * Get the cache key for a file path
1557 * @param $path string Normalized storage path
1560 private function fileCacheKey( $path ) {
1561 return wfMemcKey( 'backend', $this->getName(), 'file', sha1( $path ) );
1565 * Set the cached stat info for a file path.
1566 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1567 * salting for the case when a file is created at a path were there was none before.
1569 * @param $path string Storage path
1570 * @param $val mixed Information to cache
1572 final protected function setFileCache( $path, $val ) {
1573 $path = FileBackend
::normalizeStoragePath( $path );
1574 if ( $path === null ) {
1575 return; // invalid storage path
1577 $this->memCache
->add( $this->fileCacheKey( $path ), $val, 7*86400 );
1581 * Delete the cached stat info for a file path.
1582 * The cache key is salted for a while to prevent race conditions.
1584 * @param $path string Storage path
1586 final protected function deleteFileCache( $path ) {
1587 $path = FileBackend
::normalizeStoragePath( $path );
1588 if ( $path === null ) {
1589 return; // invalid storage path
1591 if ( !$this->memCache
->set( $this->fileCacheKey( $path ), 'PURGED', 300 ) ) {
1592 trigger_error( "Unable to delete stat cache for file $path." );
1597 * Do a batch lookup from cache for file stats for all paths
1598 * used in a list of storage paths or FileOp objects.
1599 * This loads the persistent cache values into the process cache.
1601 * @param $items Array List of storage paths or FileOps
1604 final protected function primeFileCache( array $items ) {
1605 wfProfileIn( __METHOD__
);
1606 wfProfileIn( __METHOD__
. '-' . $this->name
);
1608 $paths = array(); // list of storage paths
1609 $pathNames = array(); // (cache key => storage path)
1610 // Get all the paths/containers from the items...
1611 foreach ( $items as $item ) {
1612 if ( $item instanceof FileOp
) {
1613 $paths = array_merge( $paths, $item->storagePathsRead() );
1614 $paths = array_merge( $paths, $item->storagePathsChanged() );
1615 } elseif ( self
::isStoragePath( $item ) ) {
1616 $paths[] = FileBackend
::normalizeStoragePath( $item );
1619 // Get rid of any paths that failed normalization...
1620 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1621 // Get all the corresponding cache keys for paths...
1622 foreach ( $paths as $path ) {
1623 list( $cont, $rel, $s ) = $this->resolveStoragePath( $path );
1624 if ( $rel !== null ) { // valid path for this backend
1625 $pathNames[$this->fileCacheKey( $path )] = $path;
1628 // Get all cache entries for these container cache keys...
1629 $values = $this->memCache
->getMulti( array_keys( $pathNames ) );
1630 foreach ( $values as $cacheKey => $val ) {
1631 if ( is_array( $val ) ) {
1632 $path = $pathNames[$cacheKey];
1633 $this->cheapCache
->set( $path, 'stat', $val );
1634 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1635 $this->cheapCache
->set( $path, 'sha1',
1636 array( 'hash' => $val['sha1'], 'latest' => $val['latest'] ) );
1641 wfProfileOut( __METHOD__
. '-' . $this->name
);
1642 wfProfileOut( __METHOD__
);
1646 * Set the 'concurrency' option from a list of operation options
1648 * @param $opts array Map of operation options
1651 final protected function setConcurrencyFlags( array $opts ) {
1652 $opts['concurrency'] = 1; // off
1653 if ( $this->parallelize
=== 'implicit' ) {
1654 if ( !isset( $opts['parallelize'] ) ||
$opts['parallelize'] ) {
1655 $opts['concurrency'] = $this->concurrency
;
1657 } elseif ( $this->parallelize
=== 'explicit' ) {
1658 if ( !empty( $opts['parallelize'] ) ) {
1659 $opts['concurrency'] = $this->concurrency
;
1667 * FileBackendStore helper class for performing asynchronous file operations.
1669 * For example, calling FileBackendStore::createInternal() with the "async"
1670 * param flag may result in a Status that contains this object as a value.
1671 * This class is largely backend-specific and is mostly just "magic" to be
1672 * passed to FileBackendStore::executeOpHandlesInternal().
1674 abstract class FileBackendStoreOpHandle
{
1676 public $params = array(); // params to caller functions
1677 /** @var FileBackendStore */
1680 public $resourcesToClose = array();
1682 public $call; // string; name that identifies the function called
1685 * Close all open file handles
1689 public function closeResources() {
1690 array_map( 'fclose', $this->resourcesToClose
);
1695 * FileBackendStore helper function to handle listings that span container shards.
1696 * Do not use this class from places outside of FileBackendStore.
1698 * @ingroup FileBackend
1700 abstract class FileBackendStoreShardListIterator
implements Iterator
{
1701 /** @var FileBackendStore */
1706 protected $shardSuffixes;
1707 protected $container; // string; full container name
1708 protected $directory; // string; resolved relative path
1710 /** @var Traversable */
1712 protected $curShard = 0; // integer
1713 protected $pos = 0; // integer
1716 protected $multiShardPaths = array(); // (rel path => 1)
1719 * @param $backend FileBackendStore
1720 * @param $container string Full storage container name
1721 * @param $dir string Storage directory relative to container
1722 * @param $suffixes Array List of container shard suffixes
1723 * @param $params Array
1725 public function __construct(
1726 FileBackendStore
$backend, $container, $dir, array $suffixes, array $params
1728 $this->backend
= $backend;
1729 $this->container
= $container;
1730 $this->directory
= $dir;
1731 $this->shardSuffixes
= $suffixes;
1732 $this->params
= $params;
1736 * @see Iterator::key()
1739 public function key() {
1744 * @see Iterator::valid()
1747 public function valid() {
1748 if ( $this->iter
instanceof Iterator
) {
1749 return $this->iter
->valid();
1750 } elseif ( is_array( $this->iter
) ) {
1751 return ( current( $this->iter
) !== false ); // no paths can have this value
1753 return false; // some failure?
1757 * @see Iterator::current()
1758 * @return string|bool String or false
1760 public function current() {
1761 return ( $this->iter
instanceof Iterator
)
1762 ?
$this->iter
->current()
1763 : current( $this->iter
);
1767 * @see Iterator::next()
1770 public function next() {
1772 ( $this->iter
instanceof Iterator
) ?
$this->iter
->next() : next( $this->iter
);
1774 $continue = false; // keep scanning shards?
1775 $this->filterViaNext(); // filter out duplicates
1776 // Find the next non-empty shard if no elements are left
1777 if ( !$this->valid() ) {
1778 $this->nextShardIteratorIfNotValid();
1779 $continue = $this->valid(); // re-filter unless we ran out of shards
1781 } while ( $continue );
1785 * @see Iterator::rewind()
1788 public function rewind() {
1790 $this->curShard
= 0;
1791 $this->setIteratorFromCurrentShard();
1793 $continue = false; // keep scanning shards?
1794 $this->filterViaNext(); // filter out duplicates
1795 // Find the next non-empty shard if no elements are left
1796 if ( !$this->valid() ) {
1797 $this->nextShardIteratorIfNotValid();
1798 $continue = $this->valid(); // re-filter unless we ran out of shards
1800 } while ( $continue );
1804 * Filter out duplicate items by advancing to the next ones
1806 protected function filterViaNext() {
1807 while ( $this->valid() ) {
1808 $rel = $this->iter
->current(); // path relative to given directory
1809 $path = $this->params
['dir'] . "/{$rel}"; // full storage path
1810 if ( $this->backend
->isSingleShardPathInternal( $path ) ) {
1811 break; // path is only on one shard; no issue with duplicates
1812 } elseif ( isset( $this->multiShardPaths
[$rel] ) ) {
1813 // Don't keep listing paths that are on multiple shards
1814 ( $this->iter
instanceof Iterator
) ?
$this->iter
->next() : next( $this->iter
);
1816 $this->multiShardPaths
[$rel] = 1;
1823 * If the list iterator for this container shard is out of items,
1824 * then move on to the next container that has items.
1825 * If there are none, then it advances to the last container.
1827 protected function nextShardIteratorIfNotValid() {
1828 while ( !$this->valid() && ++
$this->curShard
< count( $this->shardSuffixes
) ) {
1829 $this->setIteratorFromCurrentShard();
1834 * Set the list iterator to that of the current container shard
1836 protected function setIteratorFromCurrentShard() {
1837 $this->iter
= $this->listFromShard(
1838 $this->container
. $this->shardSuffixes
[$this->curShard
],
1839 $this->directory
, $this->params
);
1840 // Start loading results so that current() works
1841 if ( $this->iter
) {
1842 ( $this->iter
instanceof Iterator
) ?
$this->iter
->rewind() : reset( $this->iter
);
1847 * Get the list for a given container shard
1849 * @param $container string Resolved container name
1850 * @param $dir string Resolved path relative to container
1851 * @param $params Array
1852 * @return Traversable|Array|null
1854 abstract protected function listFromShard( $container, $dir, array $params );
1858 * Iterator for listing directories
1860 class FileBackendStoreShardDirIterator
extends FileBackendStoreShardListIterator
{
1862 * @see FileBackendStoreShardListIterator::listFromShard()
1863 * @return Array|null|Traversable
1865 protected function listFromShard( $container, $dir, array $params ) {
1866 return $this->backend
->getDirectoryListInternal( $container, $dir, $params );
1871 * Iterator for listing regular files
1873 class FileBackendStoreShardFileIterator
extends FileBackendStoreShardListIterator
{
1875 * @see FileBackendStoreShardListIterator::listFromShard()
1876 * @return Array|null|Traversable
1878 protected function listFromShard( $container, $dir, array $params ) {
1879 return $this->backend
->getFileListInternal( $container, $dir, $params );