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.
100 * - dstExists : Whether a file exists at the destination (optimization).
101 * Callers can use "false" if no existing file is being changed.
103 * @param $params Array
106 final public function createInternal( array $params ) {
107 wfProfileIn( __METHOD__
);
108 wfProfileIn( __METHOD__
. '-' . $this->name
);
109 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
110 $status = Status
::newFatal( 'backend-fail-maxsize',
111 $params['dst'], $this->maxFileSizeInternal() );
113 $status = $this->doCreateInternal( $params );
114 $this->clearCache( array( $params['dst'] ) );
115 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
116 $this->deleteFileCache( $params['dst'] ); // persistent cache
119 wfProfileOut( __METHOD__
. '-' . $this->name
);
120 wfProfileOut( __METHOD__
);
125 * @see FileBackendStore::createInternal()
128 abstract protected function doCreateInternal( array $params );
131 * Store a file into the backend from a file on disk.
132 * This will overwrite any file that exists at the destination.
133 * Do not call this function from places outside FileBackend and FileOp.
136 * - src : source path on disk
137 * - dst : destination storage path
138 * - disposition : Content-Disposition header value for the destination
139 * - headers : HTTP header name/value map
140 * - async : Status will be returned immediately if supported.
141 * If the status is OK, then its value field will be
142 * set to a FileBackendStoreOpHandle object.
143 * - dstExists : Whether a file exists at the destination (optimization).
144 * Callers can use "false" if no existing file is being changed.
146 * @param $params Array
149 final public function storeInternal( array $params ) {
150 wfProfileIn( __METHOD__
);
151 wfProfileIn( __METHOD__
. '-' . $this->name
);
152 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
153 $status = Status
::newFatal( 'backend-fail-maxsize',
154 $params['dst'], $this->maxFileSizeInternal() );
156 $status = $this->doStoreInternal( $params );
157 $this->clearCache( array( $params['dst'] ) );
158 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
159 $this->deleteFileCache( $params['dst'] ); // persistent cache
162 wfProfileOut( __METHOD__
. '-' . $this->name
);
163 wfProfileOut( __METHOD__
);
168 * @see FileBackendStore::storeInternal()
171 abstract protected function doStoreInternal( array $params );
174 * Copy a file from one storage path to another in the backend.
175 * This will overwrite any file that exists at the destination.
176 * Do not call this function from places outside FileBackend and FileOp.
179 * - src : source storage path
180 * - dst : destination storage path
181 * - ignoreMissingSource : do nothing if the source file does not exist
182 * - disposition : Content-Disposition header value for the destination
183 * - async : Status will be returned immediately if supported.
184 * If the status is OK, then its value field will be
185 * set to a FileBackendStoreOpHandle object.
186 * - dstExists : Whether a file exists at the destination (optimization).
187 * Callers can use "false" if no existing file is being changed.
189 * @param $params Array
192 final public function copyInternal( array $params ) {
193 wfProfileIn( __METHOD__
);
194 wfProfileIn( __METHOD__
. '-' . $this->name
);
195 $status = $this->doCopyInternal( $params );
196 $this->clearCache( array( $params['dst'] ) );
197 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
198 $this->deleteFileCache( $params['dst'] ); // persistent cache
200 wfProfileOut( __METHOD__
. '-' . $this->name
);
201 wfProfileOut( __METHOD__
);
206 * @see FileBackendStore::copyInternal()
209 abstract protected function doCopyInternal( array $params );
212 * Delete a file at the storage path.
213 * Do not call this function from places outside FileBackend and FileOp.
216 * - src : source storage path
217 * - ignoreMissingSource : do nothing if the source file does not exist
218 * - async : Status will be returned immediately if supported.
219 * If the status is OK, then its value field will be
220 * set to a FileBackendStoreOpHandle object.
222 * @param $params Array
225 final public function deleteInternal( array $params ) {
226 wfProfileIn( __METHOD__
);
227 wfProfileIn( __METHOD__
. '-' . $this->name
);
228 $status = $this->doDeleteInternal( $params );
229 $this->clearCache( array( $params['src'] ) );
230 $this->deleteFileCache( $params['src'] ); // persistent cache
231 wfProfileOut( __METHOD__
. '-' . $this->name
);
232 wfProfileOut( __METHOD__
);
237 * @see FileBackendStore::deleteInternal()
240 abstract protected function doDeleteInternal( array $params );
243 * Move a file from one storage path to another in the backend.
244 * This will overwrite any file that exists at the destination.
245 * Do not call this function from places outside FileBackend and FileOp.
248 * - src : source storage path
249 * - dst : destination storage path
250 * - ignoreMissingSource : do nothing if the source file does not exist
251 * - disposition : Content-Disposition header value for the destination
252 * - async : Status will be returned immediately if supported.
253 * If the status is OK, then its value field will be
254 * set to a FileBackendStoreOpHandle object.
255 * - dstExists : Whether a file exists at the destination (optimization).
256 * Callers can use "false" if no existing file is being changed.
258 * @param $params Array
261 final public function moveInternal( array $params ) {
262 wfProfileIn( __METHOD__
);
263 wfProfileIn( __METHOD__
. '-' . $this->name
);
264 $status = $this->doMoveInternal( $params );
265 $this->clearCache( array( $params['src'], $params['dst'] ) );
266 $this->deleteFileCache( $params['src'] ); // persistent cache
267 if ( !isset( $params['dstExists'] ) ||
$params['dstExists'] ) {
268 $this->deleteFileCache( $params['dst'] ); // persistent cache
270 wfProfileOut( __METHOD__
. '-' . $this->name
);
271 wfProfileOut( __METHOD__
);
276 * @see FileBackendStore::moveInternal()
279 protected function doMoveInternal( array $params ) {
280 unset( $params['async'] ); // two steps, won't work here :)
281 // Copy source to dest
282 $status = $this->copyInternal( $params );
283 if ( $status->isOK() ) {
284 // Delete source (only fails due to races or medium going down)
285 $status->merge( $this->deleteInternal( array( 'src' => $params['src'] ) ) );
286 $status->setResult( true, $status->value
); // ignore delete() errors
292 * Alter metadata for a file at the storage path.
293 * Do not call this function from places outside FileBackend and FileOp.
296 * - src : source storage path
297 * - disposition : Content-Disposition header value for the destination
298 * - headers : HTTP header name/value map
299 * - async : Status will be returned immediately if supported.
300 * If the status is OK, then its value field will be
301 * set to a FileBackendStoreOpHandle object.
303 * @param $params Array
306 final public function describeInternal( array $params ) {
307 wfProfileIn( __METHOD__
);
308 wfProfileIn( __METHOD__
. '-' . $this->name
);
309 $status = $this->doDescribeInternal( $params );
310 $this->clearCache( array( $params['src'] ) );
311 $this->deleteFileCache( $params['src'] ); // persistent cache
312 wfProfileOut( __METHOD__
. '-' . $this->name
);
313 wfProfileOut( __METHOD__
);
318 * @see FileBackendStore::describeInternal()
321 protected function doDescribeInternal( array $params ) {
322 return Status
::newGood();
326 * No-op file operation that does nothing.
327 * Do not call this function from places outside FileBackend and FileOp.
329 * @param $params Array
332 final public function nullInternal( array $params ) {
333 return Status
::newGood();
337 * @see FileBackend::concatenate()
340 final public function concatenate( array $params ) {
341 wfProfileIn( __METHOD__
);
342 wfProfileIn( __METHOD__
. '-' . $this->name
);
343 $status = Status
::newGood();
345 // Try to lock the source files for the scope of this function
346 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager
::LOCK_UW
, $status );
347 if ( $status->isOK() ) {
348 // Actually do the file concatenation...
349 $start_time = microtime( true );
350 $status->merge( $this->doConcatenate( $params ) );
351 $sec = microtime( true ) - $start_time;
352 if ( !$status->isOK() ) {
353 wfDebugLog( 'FileOperation', get_class( $this ) . " failed to concatenate " .
354 count( $params['srcs'] ) . " file(s) [$sec sec]" );
358 wfProfileOut( __METHOD__
. '-' . $this->name
);
359 wfProfileOut( __METHOD__
);
364 * @see FileBackendStore::concatenate()
367 protected function doConcatenate( array $params ) {
368 $status = Status
::newGood();
370 $tmpPath = $params['dst']; // convenience
371 unset( $params['latest'] ); // sanity
372 $callback = isset( $params['callback'] )
373 ?
$params['callback']
374 : function( Status
$status, $segment ) {};
376 // Check that the specified temp file is valid...
377 wfSuppressWarnings();
378 $ok = ( is_file( $tmpPath ) && filesize( $tmpPath ) == 0 );
380 if ( !$ok ) { // not present or not empty
381 $status->fatal( 'backend-fail-opentemp', $tmpPath );
382 $callback( $status, null ); // update progress
386 // Get local FS versions of the chunks needed for the concatenation...
387 $fsFiles = $this->getLocalReferenceMulti( $params );
388 foreach ( $fsFiles as $path => &$fsFile ) {
389 if ( !$fsFile ) { // chunk failed to download?
390 $fsFile = $this->getLocalReference( array( 'src' => $path ) );
391 if ( !$fsFile ) { // retry failed?
392 $status->fatal( 'backend-fail-read', $path );
393 $callback( $status, null ); // update progress
398 unset( $fsFile ); // unset reference so we can reuse $fsFile
400 // Get a handle for the destination temp file
401 $tmpHandle = fopen( $tmpPath, 'ab' );
402 if ( $tmpHandle === false ) {
403 $status->fatal( 'backend-fail-opentemp', $tmpPath );
404 $callback( $status, null ); // update progress
408 $segment = 0; // segment number
409 // Build up the temp file using the source chunks (in order)...
410 foreach ( $fsFiles as $virtualSource => $fsFile ) {
411 ++
$segment; // first segment is "1"
412 // Get a handle to the local FS version
413 $sourceHandle = fopen( $fsFile->getPath(), 'rb' );
414 if ( $sourceHandle === false ) {
415 fclose( $tmpHandle );
416 $status->fatal( 'backend-fail-read', $virtualSource );
417 $callback( $status, null ); // update progress
420 // Append chunk to file (pass chunk size to avoid magic quotes)
421 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
422 fclose( $sourceHandle );
423 fclose( $tmpHandle );
424 $status->fatal( 'backend-fail-writetemp', $tmpPath );
425 $callback( $status , null );
428 fclose( $sourceHandle );
429 $callback( $status, $segment ); // update progress (chunk success)
431 if ( !fclose( $tmpHandle ) ) {
432 $status->fatal( 'backend-fail-closetemp', $tmpPath );
433 $callback( $status, null ); // update progress
437 clearstatcache(); // temp file changed
438 $callback( $status, null ); // update progress (full success)
444 * @see FileBackend::doPrepare()
447 final protected function doPrepare( array $params ) {
448 wfProfileIn( __METHOD__
);
449 wfProfileIn( __METHOD__
. '-' . $this->name
);
451 $status = Status
::newGood();
452 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
453 if ( $dir === null ) {
454 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
455 wfProfileOut( __METHOD__
. '-' . $this->name
);
456 wfProfileOut( __METHOD__
);
457 return $status; // invalid storage path
460 if ( $shard !== null ) { // confined to a single container/shard
461 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
462 } else { // directory is on several shards
463 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
464 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
465 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
466 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
470 wfProfileOut( __METHOD__
. '-' . $this->name
);
471 wfProfileOut( __METHOD__
);
476 * @see FileBackendStore::doPrepare()
479 protected function doPrepareInternal( $container, $dir, array $params ) {
480 return Status
::newGood();
484 * @see FileBackend::doSecure()
487 final protected function doSecure( array $params ) {
488 wfProfileIn( __METHOD__
);
489 wfProfileIn( __METHOD__
. '-' . $this->name
);
490 $status = Status
::newGood();
492 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
493 if ( $dir === null ) {
494 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
495 wfProfileOut( __METHOD__
. '-' . $this->name
);
496 wfProfileOut( __METHOD__
);
497 return $status; // invalid storage path
500 if ( $shard !== null ) { // confined to a single container/shard
501 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
502 } else { // directory is on several shards
503 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
504 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
505 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
506 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
510 wfProfileOut( __METHOD__
. '-' . $this->name
);
511 wfProfileOut( __METHOD__
);
516 * @see FileBackendStore::doSecure()
519 protected function doSecureInternal( $container, $dir, array $params ) {
520 return Status
::newGood();
524 * @see FileBackend::doPublish()
527 final protected function doPublish( array $params ) {
528 wfProfileIn( __METHOD__
);
529 wfProfileIn( __METHOD__
. '-' . $this->name
);
530 $status = Status
::newGood();
532 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
533 if ( $dir === null ) {
534 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
535 wfProfileOut( __METHOD__
. '-' . $this->name
);
536 wfProfileOut( __METHOD__
);
537 return $status; // invalid storage path
540 if ( $shard !== null ) { // confined to a single container/shard
541 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
542 } else { // directory is on several shards
543 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
544 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
545 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
546 $status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
550 wfProfileOut( __METHOD__
. '-' . $this->name
);
551 wfProfileOut( __METHOD__
);
556 * @see FileBackendStore::doPublish()
559 protected function doPublishInternal( $container, $dir, array $params ) {
560 return Status
::newGood();
564 * @see FileBackend::doClean()
567 final protected function doClean( array $params ) {
568 wfProfileIn( __METHOD__
);
569 wfProfileIn( __METHOD__
. '-' . $this->name
);
570 $status = Status
::newGood();
572 // Recursive: first delete all empty subdirs recursively
573 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
574 $subDirsRel = $this->getTopDirectoryList( array( 'dir' => $params['dir'] ) );
575 if ( $subDirsRel !== null ) { // no errors
576 foreach ( $subDirsRel as $subDirRel ) {
577 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
578 $status->merge( $this->doClean( array( 'dir' => $subDir ) +
$params ) );
580 unset( $subDirsRel ); // free directory for rmdir() on Windows (for FS backends)
584 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
585 if ( $dir === null ) {
586 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
587 wfProfileOut( __METHOD__
. '-' . $this->name
);
588 wfProfileOut( __METHOD__
);
589 return $status; // invalid storage path
592 // Attempt to lock this directory...
593 $filesLockEx = array( $params['dir'] );
594 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
595 if ( !$status->isOK() ) {
596 wfProfileOut( __METHOD__
. '-' . $this->name
);
597 wfProfileOut( __METHOD__
);
598 return $status; // abort
601 if ( $shard !== null ) { // confined to a single container/shard
602 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
603 $this->deleteContainerCache( $fullCont ); // purge cache
604 } else { // directory is on several shards
605 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
606 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
607 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
608 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
609 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
613 wfProfileOut( __METHOD__
. '-' . $this->name
);
614 wfProfileOut( __METHOD__
);
619 * @see FileBackendStore::doClean()
622 protected function doCleanInternal( $container, $dir, array $params ) {
623 return Status
::newGood();
627 * @see FileBackend::fileExists()
630 final public function fileExists( array $params ) {
631 wfProfileIn( __METHOD__
);
632 wfProfileIn( __METHOD__
. '-' . $this->name
);
633 $stat = $this->getFileStat( $params );
634 wfProfileOut( __METHOD__
. '-' . $this->name
);
635 wfProfileOut( __METHOD__
);
636 return ( $stat === null ) ?
null : (bool)$stat; // null => failure
640 * @see FileBackend::getFileTimestamp()
643 final public function getFileTimestamp( array $params ) {
644 wfProfileIn( __METHOD__
);
645 wfProfileIn( __METHOD__
. '-' . $this->name
);
646 $stat = $this->getFileStat( $params );
647 wfProfileOut( __METHOD__
. '-' . $this->name
);
648 wfProfileOut( __METHOD__
);
649 return $stat ?
$stat['mtime'] : false;
653 * @see FileBackend::getFileSize()
656 final public function getFileSize( array $params ) {
657 wfProfileIn( __METHOD__
);
658 wfProfileIn( __METHOD__
. '-' . $this->name
);
659 $stat = $this->getFileStat( $params );
660 wfProfileOut( __METHOD__
. '-' . $this->name
);
661 wfProfileOut( __METHOD__
);
662 return $stat ?
$stat['size'] : false;
666 * @see FileBackend::getFileStat()
669 final public function getFileStat( array $params ) {
670 $path = self
::normalizeStoragePath( $params['src'] );
671 if ( $path === null ) {
672 return false; // invalid storage path
674 wfProfileIn( __METHOD__
);
675 wfProfileIn( __METHOD__
. '-' . $this->name
);
676 $latest = !empty( $params['latest'] ); // use latest data?
677 if ( !$this->cheapCache
->has( $path, 'stat', self
::CACHE_TTL
) ) {
678 $this->primeFileCache( array( $path ) ); // check persistent cache
680 if ( $this->cheapCache
->has( $path, 'stat', self
::CACHE_TTL
) ) {
681 $stat = $this->cheapCache
->get( $path, 'stat' );
682 // If we want the latest data, check that this cached
683 // value was in fact fetched with the latest available data.
684 if ( is_array( $stat ) ) {
685 if ( !$latest ||
$stat['latest'] ) {
686 wfProfileOut( __METHOD__
. '-' . $this->name
);
687 wfProfileOut( __METHOD__
);
690 } elseif ( in_array( $stat, array( 'NOT_EXIST', 'NOT_EXIST_LATEST' ) ) ) {
691 if ( !$latest ||
$stat === 'NOT_EXIST_LATEST' ) {
692 wfProfileOut( __METHOD__
. '-' . $this->name
);
693 wfProfileOut( __METHOD__
);
698 wfProfileIn( __METHOD__
. '-miss' );
699 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
700 $stat = $this->doGetFileStat( $params );
701 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
702 wfProfileOut( __METHOD__
. '-miss' );
703 if ( is_array( $stat ) ) { // file exists
704 $stat['latest'] = $latest;
705 $this->cheapCache
->set( $path, 'stat', $stat );
706 $this->setFileCache( $path, $stat ); // update persistent cache
707 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
708 $this->cheapCache
->set( $path, 'sha1',
709 array( 'hash' => $stat['sha1'], 'latest' => $latest ) );
711 } elseif ( $stat === false ) { // file does not exist
712 $this->cheapCache
->set( $path, 'stat', $latest ?
'NOT_EXIST_LATEST' : 'NOT_EXIST' );
713 wfDebug( __METHOD__
. ": File $path does not exist.\n" );
714 } else { // an error occurred
715 wfDebug( __METHOD__
. ": Could not stat file $path.\n" );
717 wfProfileOut( __METHOD__
. '-' . $this->name
);
718 wfProfileOut( __METHOD__
);
723 * @see FileBackendStore::getFileStat()
725 abstract protected function doGetFileStat( array $params );
728 * @see FileBackend::getFileContentsMulti()
731 public function getFileContentsMulti( array $params ) {
732 wfProfileIn( __METHOD__
);
733 wfProfileIn( __METHOD__
. '-' . $this->name
);
735 $params = $this->setConcurrencyFlags( $params );
736 $contents = $this->doGetFileContentsMulti( $params );
738 wfProfileOut( __METHOD__
. '-' . $this->name
);
739 wfProfileOut( __METHOD__
);
744 * @see FileBackendStore::getFileContentsMulti()
747 protected function doGetFileContentsMulti( array $params ) {
749 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
750 wfSuppressWarnings();
751 $contents[$path] = $fsFile ?
file_get_contents( $fsFile->getPath() ) : false;
758 * @see FileBackend::getFileSha1Base36()
759 * @return bool|string
761 final public function getFileSha1Base36( array $params ) {
762 $path = self
::normalizeStoragePath( $params['src'] );
763 if ( $path === null ) {
764 return false; // invalid storage path
766 wfProfileIn( __METHOD__
);
767 wfProfileIn( __METHOD__
. '-' . $this->name
);
768 $latest = !empty( $params['latest'] ); // use latest data?
769 if ( $this->cheapCache
->has( $path, 'sha1', self
::CACHE_TTL
) ) {
770 $stat = $this->cheapCache
->get( $path, 'sha1' );
771 // If we want the latest data, check that this cached
772 // value was in fact fetched with the latest available data.
773 if ( !$latest ||
$stat['latest'] ) {
774 wfProfileOut( __METHOD__
. '-' . $this->name
);
775 wfProfileOut( __METHOD__
);
776 return $stat['hash'];
779 wfProfileIn( __METHOD__
. '-miss' );
780 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
781 $hash = $this->doGetFileSha1Base36( $params );
782 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
783 wfProfileOut( __METHOD__
. '-miss' );
784 if ( $hash ) { // don't cache negatives
785 $this->cheapCache
->set( $path, 'sha1',
786 array( 'hash' => $hash, 'latest' => $latest ) );
788 wfProfileOut( __METHOD__
. '-' . $this->name
);
789 wfProfileOut( __METHOD__
);
794 * @see FileBackendStore::getFileSha1Base36()
795 * @return bool|string
797 protected function doGetFileSha1Base36( array $params ) {
798 $fsFile = $this->getLocalReference( $params );
802 return $fsFile->getSha1Base36();
807 * @see FileBackend::getFileProps()
810 final public function getFileProps( array $params ) {
811 wfProfileIn( __METHOD__
);
812 wfProfileIn( __METHOD__
. '-' . $this->name
);
813 $fsFile = $this->getLocalReference( $params );
814 $props = $fsFile ?
$fsFile->getProps() : FSFile
::placeholderProps();
815 wfProfileOut( __METHOD__
. '-' . $this->name
);
816 wfProfileOut( __METHOD__
);
821 * @see FileBackend::getLocalReferenceMulti()
824 final public function getLocalReferenceMulti( array $params ) {
825 wfProfileIn( __METHOD__
);
826 wfProfileIn( __METHOD__
. '-' . $this->name
);
828 $params = $this->setConcurrencyFlags( $params );
830 $fsFiles = array(); // (path => FSFile)
831 $latest = !empty( $params['latest'] ); // use latest data?
832 // Reuse any files already in process cache...
833 foreach ( $params['srcs'] as $src ) {
834 $path = self
::normalizeStoragePath( $src );
835 if ( $path === null ) {
836 $fsFiles[$src] = null; // invalid storage path
837 } elseif ( $this->expensiveCache
->has( $path, 'localRef' ) ) {
838 $val = $this->expensiveCache
->get( $path, 'localRef' );
839 // If we want the latest data, check that this cached
840 // value was in fact fetched with the latest available data.
841 if ( !$latest ||
$val['latest'] ) {
842 $fsFiles[$src] = $val['object'];
846 // Fetch local references of any remaning files...
847 $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
848 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
849 $fsFiles[$path] = $fsFile;
850 if ( $fsFile ) { // update the process cache...
851 $this->expensiveCache
->set( $path, 'localRef',
852 array( 'object' => $fsFile, 'latest' => $latest ) );
856 wfProfileOut( __METHOD__
. '-' . $this->name
);
857 wfProfileOut( __METHOD__
);
862 * @see FileBackendStore::getLocalReferenceMulti()
865 protected function doGetLocalReferenceMulti( array $params ) {
866 return $this->doGetLocalCopyMulti( $params );
870 * @see FileBackend::getLocalCopyMulti()
873 final public function getLocalCopyMulti( array $params ) {
874 wfProfileIn( __METHOD__
);
875 wfProfileIn( __METHOD__
. '-' . $this->name
);
877 $params = $this->setConcurrencyFlags( $params );
878 $tmpFiles = $this->doGetLocalCopyMulti( $params );
880 wfProfileOut( __METHOD__
. '-' . $this->name
);
881 wfProfileOut( __METHOD__
);
886 * @see FileBackendStore::getLocalCopyMulti()
889 abstract protected function doGetLocalCopyMulti( array $params );
892 * @see FileBackend::getFileHttpUrl()
893 * @return string|null
895 public function getFileHttpUrl( array $params ) {
896 return null; // not supported
900 * @see FileBackend::streamFile()
903 final public function streamFile( array $params ) {
904 wfProfileIn( __METHOD__
);
905 wfProfileIn( __METHOD__
. '-' . $this->name
);
906 $status = Status
::newGood();
908 $info = $this->getFileStat( $params );
909 if ( !$info ) { // let StreamFile handle the 404
910 $status->fatal( 'backend-fail-notexists', $params['src'] );
913 // Set output buffer and HTTP headers for stream
914 $extraHeaders = isset( $params['headers'] ) ?
$params['headers'] : array();
915 $res = StreamFile
::prepareForStream( $params['src'], $info, $extraHeaders );
916 if ( $res == StreamFile
::NOT_MODIFIED
) {
917 // do nothing; client cache is up to date
918 } elseif ( $res == StreamFile
::READY_STREAM
) {
919 wfProfileIn( __METHOD__
. '-send' );
920 wfProfileIn( __METHOD__
. '-send-' . $this->name
);
921 $status = $this->doStreamFile( $params );
922 wfProfileOut( __METHOD__
. '-send-' . $this->name
);
923 wfProfileOut( __METHOD__
. '-send' );
924 if ( !$status->isOK() ) {
925 // Per bug 41113, nasty things can happen if bad cache entries get
926 // stuck in cache. It's also possible that this error can come up
927 // with simple race conditions. Clear out the stat cache to be safe.
928 $this->clearCache( array( $params['src'] ) );
929 $this->deleteFileCache( $params['src'] );
930 trigger_error( "Bad stat cache or race condition for file {$params['src']}." );
933 $status->fatal( 'backend-fail-stream', $params['src'] );
936 wfProfileOut( __METHOD__
. '-' . $this->name
);
937 wfProfileOut( __METHOD__
);
942 * @see FileBackendStore::streamFile()
945 protected function doStreamFile( array $params ) {
946 $status = Status
::newGood();
948 $fsFile = $this->getLocalReference( $params );
950 $status->fatal( 'backend-fail-stream', $params['src'] );
951 } elseif ( !readfile( $fsFile->getPath() ) ) {
952 $status->fatal( 'backend-fail-stream', $params['src'] );
959 * @see FileBackend::directoryExists()
962 final public function directoryExists( array $params ) {
963 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
964 if ( $dir === null ) {
965 return false; // invalid storage path
967 if ( $shard !== null ) { // confined to a single container/shard
968 return $this->doDirectoryExists( $fullCont, $dir, $params );
969 } else { // directory is on several shards
970 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
971 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
972 $res = false; // response
973 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
974 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
978 } elseif ( $exists === null ) { // error?
979 $res = null; // if we don't find anything, it is indeterminate
987 * @see FileBackendStore::directoryExists()
989 * @param $container string Resolved container name
990 * @param $dir string Resolved path relative to container
991 * @param $params Array
994 abstract protected function doDirectoryExists( $container, $dir, array $params );
997 * @see FileBackend::getDirectoryList()
998 * @return Traversable|Array|null Returns null on failure
1000 final public function getDirectoryList( array $params ) {
1001 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
1002 if ( $dir === null ) { // invalid storage path
1005 if ( $shard !== null ) {
1006 // File listing is confined to a single container/shard
1007 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
1009 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
1010 // File listing spans multiple containers/shards
1011 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
1012 return new FileBackendStoreShardDirIterator( $this,
1013 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
1018 * Do not call this function from places outside FileBackend
1020 * @see FileBackendStore::getDirectoryList()
1022 * @param $container string Resolved container name
1023 * @param $dir string Resolved path relative to container
1024 * @param $params Array
1025 * @return Traversable|Array|null Returns null on failure
1027 abstract public function getDirectoryListInternal( $container, $dir, array $params );
1030 * @see FileBackend::getFileList()
1031 * @return Traversable|Array|null Returns null on failure
1033 final public function getFileList( array $params ) {
1034 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
1035 if ( $dir === null ) { // invalid storage path
1038 if ( $shard !== null ) {
1039 // File listing is confined to a single container/shard
1040 return $this->getFileListInternal( $fullCont, $dir, $params );
1042 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
1043 // File listing spans multiple containers/shards
1044 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
1045 return new FileBackendStoreShardFileIterator( $this,
1046 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
1051 * Do not call this function from places outside FileBackend
1053 * @see FileBackendStore::getFileList()
1055 * @param $container string Resolved container name
1056 * @param $dir string Resolved path relative to container
1057 * @param $params Array
1058 * @return Traversable|Array|null Returns null on failure
1060 abstract public function getFileListInternal( $container, $dir, array $params );
1063 * Return a list of FileOp objects from a list of operations.
1064 * Do not call this function from places outside FileBackend.
1066 * The result must have the same number of items as the input.
1067 * An exception is thrown if an unsupported operation is requested.
1069 * @param $ops Array Same format as doOperations()
1070 * @return Array List of FileOp objects
1071 * @throws MWException
1073 final public function getOperationsInternal( array $ops ) {
1074 $supportedOps = array(
1075 'store' => 'StoreFileOp',
1076 'copy' => 'CopyFileOp',
1077 'move' => 'MoveFileOp',
1078 'delete' => 'DeleteFileOp',
1079 'create' => 'CreateFileOp',
1080 'describe' => 'DescribeFileOp',
1081 'null' => 'NullFileOp'
1084 $performOps = array(); // array of FileOp objects
1085 // Build up ordered array of FileOps...
1086 foreach ( $ops as $operation ) {
1087 $opName = $operation['op'];
1088 if ( isset( $supportedOps[$opName] ) ) {
1089 $class = $supportedOps[$opName];
1090 // Get params for this operation
1091 $params = $operation;
1092 // Append the FileOp class
1093 $performOps[] = new $class( $this, $params );
1095 throw new MWException( "Operation '$opName' is not supported." );
1103 * Get a list of storage paths to lock for a list of operations
1104 * Returns an array with 'sh' (shared) and 'ex' (exclusive) keys,
1105 * each corresponding to a list of storage paths to be locked.
1106 * All returned paths are normalized.
1108 * @param $performOps Array List of FileOp objects
1109 * @return Array ('sh' => list of paths, 'ex' => list of paths)
1111 final public function getPathsToLockForOpsInternal( array $performOps ) {
1112 // Build up a list of files to lock...
1113 $paths = array( 'sh' => array(), 'ex' => array() );
1114 foreach ( $performOps as $fileOp ) {
1115 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1116 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1118 // Optimization: if doing an EX lock anyway, don't also set an SH one
1119 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1120 // Get a shared lock on the parent directory of each path changed
1121 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1127 * @see FileBackend::getScopedLocksForOps()
1130 public function getScopedLocksForOps( array $ops, Status
$status ) {
1131 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1133 $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status ),
1134 $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status )
1139 * @see FileBackend::doOperationsInternal()
1142 final protected function doOperationsInternal( array $ops, array $opts ) {
1143 wfProfileIn( __METHOD__
);
1144 wfProfileIn( __METHOD__
. '-' . $this->name
);
1145 $status = Status
::newGood();
1147 // Fix up custom header name/value pairs...
1148 $ops = array_map( array( $this, 'stripInvalidHeadersFromOp' ), $ops );
1150 // Build up a list of FileOps...
1151 $performOps = $this->getOperationsInternal( $ops );
1153 // Acquire any locks as needed...
1154 if ( empty( $opts['nonLocking'] ) ) {
1155 // Build up a list of files to lock...
1156 $paths = $this->getPathsToLockForOpsInternal( $performOps );
1157 // Try to lock those files for the scope of this function...
1158 $scopeLockS = $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status );
1159 $scopeLockE = $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status );
1160 if ( !$status->isOK() ) {
1161 wfProfileOut( __METHOD__
. '-' . $this->name
);
1162 wfProfileOut( __METHOD__
);
1163 return $status; // abort
1167 // Clear any file cache entries (after locks acquired)
1168 if ( empty( $opts['preserveCache'] ) ) {
1169 $this->clearCache();
1172 // Load from the persistent file and container caches
1173 $this->primeFileCache( $performOps );
1174 $this->primeContainerCache( $performOps );
1176 // Actually attempt the operation batch...
1177 $opts = $this->setConcurrencyFlags( $opts );
1178 $subStatus = FileOpBatch
::attempt( $performOps, $opts, $this->fileJournal
);
1180 // Merge errors into status fields
1181 $status->merge( $subStatus );
1182 $status->success
= $subStatus->success
; // not done in merge()
1184 wfProfileOut( __METHOD__
. '-' . $this->name
);
1185 wfProfileOut( __METHOD__
);
1190 * @see FileBackend::doQuickOperationsInternal()
1192 * @throws MWException
1194 final protected function doQuickOperationsInternal( array $ops ) {
1195 wfProfileIn( __METHOD__
);
1196 wfProfileIn( __METHOD__
. '-' . $this->name
);
1197 $status = Status
::newGood();
1199 // Fix up custom header name/value pairs...
1200 $ops = array_map( array( $this, 'stripInvalidHeadersFromOp' ), $ops );
1202 // Clear any file cache entries
1203 $this->clearCache();
1205 $supportedOps = array( 'create', 'store', 'copy', 'move', 'delete', 'null' );
1206 $async = ( $this->parallelize
=== 'implicit' );
1207 $maxConcurrency = $this->concurrency
; // throttle
1209 $statuses = array(); // array of (index => Status)
1210 $fileOpHandles = array(); // list of (index => handle) arrays
1211 $curFileOpHandles = array(); // current handle batch
1212 // Perform the sync-only ops and build up op handles for the async ops...
1213 foreach ( $ops as $index => $params ) {
1214 if ( !in_array( $params['op'], $supportedOps ) ) {
1215 wfProfileOut( __METHOD__
. '-' . $this->name
);
1216 wfProfileOut( __METHOD__
);
1217 throw new MWException( "Operation '{$params['op']}' is not supported." );
1219 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1220 $subStatus = $this->$method( array( 'async' => $async ) +
$params );
1221 if ( $subStatus->value
instanceof FileBackendStoreOpHandle
) { // async
1222 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1223 $fileOpHandles[] = $curFileOpHandles; // push this batch
1224 $curFileOpHandles = array();
1226 $curFileOpHandles[$index] = $subStatus->value
; // keep index
1227 } else { // error or completed
1228 $statuses[$index] = $subStatus; // keep index
1231 if ( count( $curFileOpHandles ) ) {
1232 $fileOpHandles[] = $curFileOpHandles; // last batch
1234 // Do all the async ops that can be done concurrently...
1235 foreach ( $fileOpHandles as $fileHandleBatch ) {
1236 $statuses = $statuses +
$this->executeOpHandlesInternal( $fileHandleBatch );
1238 // Marshall and merge all the responses...
1239 foreach ( $statuses as $index => $subStatus ) {
1240 $status->merge( $subStatus );
1241 if ( $subStatus->isOK() ) {
1242 $status->success
[$index] = true;
1243 ++
$status->successCount
;
1245 $status->success
[$index] = false;
1246 ++
$status->failCount
;
1250 wfProfileOut( __METHOD__
. '-' . $this->name
);
1251 wfProfileOut( __METHOD__
);
1256 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1257 * The resulting Status object fields will correspond
1258 * to the order in which the handles where given.
1260 * @param $handles Array List of FileBackendStoreOpHandle objects
1261 * @return Array Map of Status objects
1262 * @throws MWException
1264 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1265 wfProfileIn( __METHOD__
);
1266 wfProfileIn( __METHOD__
. '-' . $this->name
);
1267 foreach ( $fileOpHandles as $fileOpHandle ) {
1268 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle
) ) {
1269 throw new MWException( "Given a non-FileBackendStoreOpHandle object." );
1270 } elseif ( $fileOpHandle->backend
->getName() !== $this->getName() ) {
1271 throw new MWException( "Given a FileBackendStoreOpHandle for the wrong backend." );
1274 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1275 foreach ( $fileOpHandles as $fileOpHandle ) {
1276 $fileOpHandle->closeResources();
1278 wfProfileOut( __METHOD__
. '-' . $this->name
);
1279 wfProfileOut( __METHOD__
);
1284 * @see FileBackendStore::executeOpHandlesInternal()
1285 * @param array $fileOpHandles
1286 * @throws MWException
1287 * @return Array List of corresponding Status objects
1289 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1290 foreach ( $fileOpHandles as $fileOpHandle ) { // OK if empty
1291 throw new MWException( "This backend supports no asynchronous operations." );
1297 * Strip long HTTP headers from a file operation
1299 * @param $op array Same format as doOperation()
1302 protected function stripInvalidHeadersFromOp( array $op ) {
1303 if ( isset( $op['headers'] ) ) {
1304 foreach ( $op['headers'] as $name => $value ) {
1305 if ( strlen( $name ) > 255 ||
strlen( $value ) > 255 ) {
1306 trigger_error( "Header '$name: $value' is too long." );
1307 unset( $op['headers'][$name] );
1308 } elseif ( !strlen( $value ) ) {
1309 $op['headers'][$name] = ''; // null/false => ""
1317 * @see FileBackend::preloadCache()
1319 final public function preloadCache( array $paths ) {
1320 $fullConts = array(); // full container names
1321 foreach ( $paths as $path ) {
1322 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1323 $fullConts[] = $fullCont;
1325 // Load from the persistent file and container caches
1326 $this->primeContainerCache( $fullConts );
1327 $this->primeFileCache( $paths );
1331 * @see FileBackend::clearCache()
1333 final public function clearCache( array $paths = null ) {
1334 if ( is_array( $paths ) ) {
1335 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1336 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1338 if ( $paths === null ) {
1339 $this->cheapCache
->clear();
1340 $this->expensiveCache
->clear();
1342 foreach ( $paths as $path ) {
1343 $this->cheapCache
->clear( $path );
1344 $this->expensiveCache
->clear( $path );
1347 $this->doClearCache( $paths );
1351 * Clears any additional stat caches for storage paths
1353 * @see FileBackend::clearCache()
1355 * @param $paths Array Storage paths (optional)
1358 protected function doClearCache( array $paths = null ) {}
1361 * Is this a key/value store where directories are just virtual?
1362 * Virtual directories exists in so much as files exists that are
1363 * prefixed with the directory path followed by a forward slash.
1367 abstract protected function directoriesAreVirtual();
1370 * Check if a container name is valid.
1371 * This checks for for length and illegal characters.
1373 * @param $container string
1376 final protected static function isValidContainerName( $container ) {
1377 // This accounts for Swift and S3 restrictions while leaving room
1378 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1379 // This disallows directory separators or traversal characters.
1380 // Note that matching strings URL encode to the same string;
1381 // in Swift, the length restriction is *after* URL encoding.
1382 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1386 * Splits a storage path into an internal container name,
1387 * an internal relative file name, and a container shard suffix.
1388 * Any shard suffix is already appended to the internal container name.
1389 * This also checks that the storage path is valid and within this backend.
1391 * If the container is sharded but a suffix could not be determined,
1392 * this means that the path can only refer to a directory and can only
1393 * be scanned by looking in all the container shards.
1395 * @param $storagePath string
1396 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1398 final protected function resolveStoragePath( $storagePath ) {
1399 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1400 if ( $backend === $this->name
) { // must be for this backend
1401 $relPath = self
::normalizeContainerPath( $relPath );
1402 if ( $relPath !== null ) {
1403 // Get shard for the normalized path if this container is sharded
1404 $cShard = $this->getContainerShard( $container, $relPath );
1405 // Validate and sanitize the relative path (backend-specific)
1406 $relPath = $this->resolveContainerPath( $container, $relPath );
1407 if ( $relPath !== null ) {
1408 // Prepend any wiki ID prefix to the container name
1409 $container = $this->fullContainerName( $container );
1410 if ( self
::isValidContainerName( $container ) ) {
1411 // Validate and sanitize the container name (backend-specific)
1412 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1413 if ( $container !== null ) {
1414 return array( $container, $relPath, $cShard );
1420 return array( null, null, null );
1424 * Like resolveStoragePath() except null values are returned if
1425 * the container is sharded and the shard could not be determined.
1427 * @see FileBackendStore::resolveStoragePath()
1429 * @param $storagePath string
1430 * @return Array (container, path) or (null, null) if invalid
1432 final protected function resolveStoragePathReal( $storagePath ) {
1433 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1434 if ( $cShard !== null ) {
1435 return array( $container, $relPath );
1437 return array( null, null );
1441 * Get the container name shard suffix for a given path.
1442 * Any empty suffix means the container is not sharded.
1444 * @param $container string Container name
1445 * @param $relPath string Storage path relative to the container
1446 * @return string|null Returns null if shard could not be determined
1448 final protected function getContainerShard( $container, $relPath ) {
1449 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1450 if ( $levels == 1 ||
$levels == 2 ) {
1451 // Hash characters are either base 16 or 36
1452 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1453 // Get a regex that represents the shard portion of paths.
1454 // The concatenation of the captures gives us the shard.
1455 if ( $levels === 1 ) { // 16 or 36 shards per container
1456 $hashDirRegex = '(' . $char . ')';
1457 } else { // 256 or 1296 shards per container
1458 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1459 $hashDirRegex = $char . '/(' . $char . '{2})';
1460 } else { // short hash dir format (e.g. "a/b/c")
1461 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1464 // Allow certain directories to be above the hash dirs so as
1465 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1466 // They must be 2+ chars to avoid any hash directory ambiguity.
1468 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1469 return '.' . implode( '', array_slice( $m, 1 ) );
1471 return null; // failed to match
1473 return ''; // no sharding
1477 * Check if a storage path maps to a single shard.
1478 * Container dirs like "a", where the container shards on "x/xy",
1479 * can reside on several shards. Such paths are tricky to handle.
1481 * @param $storagePath string Storage path
1484 final public function isSingleShardPathInternal( $storagePath ) {
1485 list( $c, $r, $shard ) = $this->resolveStoragePath( $storagePath );
1486 return ( $shard !== null );
1490 * Get the sharding config for a container.
1491 * If greater than 0, then all file storage paths within
1492 * the container are required to be hashed accordingly.
1494 * @param $container string
1495 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
1497 final protected function getContainerHashLevels( $container ) {
1498 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1499 $config = $this->shardViaHashLevels
[$container];
1500 $hashLevels = (int)$config['levels'];
1501 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1502 $hashBase = (int)$config['base'];
1503 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1504 return array( $hashLevels, $hashBase, $config['repeat'] );
1508 return array( 0, 0, false ); // no sharding
1512 * Get a list of full container shard suffixes for a container
1514 * @param $container string
1517 final protected function getContainerSuffixes( $container ) {
1519 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1520 if ( $digits > 0 ) {
1521 $numShards = pow( $base, $digits );
1522 for ( $index = 0; $index < $numShards; $index++
) {
1523 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1530 * Get the full container name, including the wiki ID prefix
1532 * @param $container string
1535 final protected function fullContainerName( $container ) {
1536 if ( $this->wikiId
!= '' ) {
1537 return "{$this->wikiId}-$container";
1544 * Resolve a container name, checking if it's allowed by the backend.
1545 * This is intended for internal use, such as encoding illegal chars.
1546 * Subclasses can override this to be more restrictive.
1548 * @param $container string
1549 * @return string|null
1551 protected function resolveContainerName( $container ) {
1556 * Resolve a relative storage path, checking if it's allowed by the backend.
1557 * This is intended for internal use, such as encoding illegal chars or perhaps
1558 * getting absolute paths (e.g. FS based backends). Note that the relative path
1559 * may be the empty string (e.g. the path is simply to the container).
1561 * @param $container string Container name
1562 * @param $relStoragePath string Storage path relative to the container
1563 * @return string|null Path or null if not valid
1565 protected function resolveContainerPath( $container, $relStoragePath ) {
1566 return $relStoragePath;
1570 * Get the cache key for a container
1572 * @param $container string Resolved container name
1575 private function containerCacheKey( $container ) {
1576 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1580 * Set the cached info for a container
1582 * @param $container string Resolved container name
1583 * @param $val mixed Information to cache
1585 final protected function setContainerCache( $container, $val ) {
1586 $this->memCache
->add( $this->containerCacheKey( $container ), $val, 14*86400 );
1590 * Delete the cached info for a container.
1591 * The cache key is salted for a while to prevent race conditions.
1593 * @param $container string Resolved container name
1595 final protected function deleteContainerCache( $container ) {
1596 if ( !$this->memCache
->set( $this->containerCacheKey( $container ), 'PURGED', 300 ) ) {
1597 trigger_error( "Unable to delete stat cache for container $container." );
1602 * Do a batch lookup from cache for container stats for all containers
1603 * used in a list of container names, storage paths, or FileOp objects.
1604 * This loads the persistent cache values into the process cache.
1606 * @param $items Array
1609 final protected function primeContainerCache( array $items ) {
1610 wfProfileIn( __METHOD__
);
1611 wfProfileIn( __METHOD__
. '-' . $this->name
);
1613 $paths = array(); // list of storage paths
1614 $contNames = array(); // (cache key => resolved container name)
1615 // Get all the paths/containers from the items...
1616 foreach ( $items as $item ) {
1617 if ( $item instanceof FileOp
) {
1618 $paths = array_merge( $paths, $item->storagePathsRead() );
1619 $paths = array_merge( $paths, $item->storagePathsChanged() );
1620 } elseif ( self
::isStoragePath( $item ) ) {
1622 } elseif ( is_string( $item ) ) { // full container name
1623 $contNames[$this->containerCacheKey( $item )] = $item;
1626 // Get all the corresponding cache keys for paths...
1627 foreach ( $paths as $path ) {
1628 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1629 if ( $fullCont !== null ) { // valid path for this backend
1630 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1634 $contInfo = array(); // (resolved container name => cache value)
1635 // Get all cache entries for these container cache keys...
1636 $values = $this->memCache
->getMulti( array_keys( $contNames ) );
1637 foreach ( $values as $cacheKey => $val ) {
1638 $contInfo[$contNames[$cacheKey]] = $val;
1641 // Populate the container process cache for the backend...
1642 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1644 wfProfileOut( __METHOD__
. '-' . $this->name
);
1645 wfProfileOut( __METHOD__
);
1649 * Fill the backend-specific process cache given an array of
1650 * resolved container names and their corresponding cached info.
1651 * Only containers that actually exist should appear in the map.
1653 * @param $containerInfo Array Map of resolved container names to cached info
1656 protected function doPrimeContainerCache( array $containerInfo ) {}
1659 * Get the cache key for a file path
1661 * @param $path string Normalized storage path
1664 private function fileCacheKey( $path ) {
1665 return wfMemcKey( 'backend', $this->getName(), 'file', sha1( $path ) );
1669 * Set the cached stat info for a file path.
1670 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1671 * salting for the case when a file is created at a path were there was none before.
1673 * @param $path string Storage path
1674 * @param $val mixed Information to cache
1676 final protected function setFileCache( $path, $val ) {
1677 $path = FileBackend
::normalizeStoragePath( $path );
1678 if ( $path === null ) {
1679 return; // invalid storage path
1681 $this->memCache
->add( $this->fileCacheKey( $path ), $val, 7*86400 );
1685 * Delete the cached stat info for a file path.
1686 * The cache key is salted for a while to prevent race conditions.
1687 * Since negatives (404s) are not cached, this does not need to be called when
1688 * a file is created at a path were there was none before.
1690 * @param $path string Storage path
1692 final protected function deleteFileCache( $path ) {
1693 $path = FileBackend
::normalizeStoragePath( $path );
1694 if ( $path === null ) {
1695 return; // invalid storage path
1697 if ( !$this->memCache
->set( $this->fileCacheKey( $path ), 'PURGED', 300 ) ) {
1698 trigger_error( "Unable to delete stat cache for file $path." );
1703 * Do a batch lookup from cache for file stats for all paths
1704 * used in a list of storage paths or FileOp objects.
1705 * This loads the persistent cache values into the process cache.
1707 * @param $items Array List of storage paths or FileOps
1710 final protected function primeFileCache( array $items ) {
1711 wfProfileIn( __METHOD__
);
1712 wfProfileIn( __METHOD__
. '-' . $this->name
);
1714 $paths = array(); // list of storage paths
1715 $pathNames = array(); // (cache key => storage path)
1716 // Get all the paths/containers from the items...
1717 foreach ( $items as $item ) {
1718 if ( $item instanceof FileOp
) {
1719 $paths = array_merge( $paths, $item->storagePathsRead() );
1720 $paths = array_merge( $paths, $item->storagePathsChanged() );
1721 } elseif ( self
::isStoragePath( $item ) ) {
1722 $paths[] = FileBackend
::normalizeStoragePath( $item );
1725 // Get rid of any paths that failed normalization...
1726 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1727 // Get all the corresponding cache keys for paths...
1728 foreach ( $paths as $path ) {
1729 list( $cont, $rel, $s ) = $this->resolveStoragePath( $path );
1730 if ( $rel !== null ) { // valid path for this backend
1731 $pathNames[$this->fileCacheKey( $path )] = $path;
1734 // Get all cache entries for these container cache keys...
1735 $values = $this->memCache
->getMulti( array_keys( $pathNames ) );
1736 foreach ( $values as $cacheKey => $val ) {
1737 if ( is_array( $val ) ) {
1738 $path = $pathNames[$cacheKey];
1739 $this->cheapCache
->set( $path, 'stat', $val );
1740 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1741 $this->cheapCache
->set( $path, 'sha1',
1742 array( 'hash' => $val['sha1'], 'latest' => $val['latest'] ) );
1747 wfProfileOut( __METHOD__
. '-' . $this->name
);
1748 wfProfileOut( __METHOD__
);
1752 * Set the 'concurrency' option from a list of operation options
1754 * @param $opts array Map of operation options
1757 final protected function setConcurrencyFlags( array $opts ) {
1758 $opts['concurrency'] = 1; // off
1759 if ( $this->parallelize
=== 'implicit' ) {
1760 if ( !isset( $opts['parallelize'] ) ||
$opts['parallelize'] ) {
1761 $opts['concurrency'] = $this->concurrency
;
1763 } elseif ( $this->parallelize
=== 'explicit' ) {
1764 if ( !empty( $opts['parallelize'] ) ) {
1765 $opts['concurrency'] = $this->concurrency
;
1773 * FileBackendStore helper class for performing asynchronous file operations.
1775 * For example, calling FileBackendStore::createInternal() with the "async"
1776 * param flag may result in a Status that contains this object as a value.
1777 * This class is largely backend-specific and is mostly just "magic" to be
1778 * passed to FileBackendStore::executeOpHandlesInternal().
1780 abstract class FileBackendStoreOpHandle
{
1782 public $params = array(); // params to caller functions
1783 /** @var FileBackendStore */
1786 public $resourcesToClose = array();
1788 public $call; // string; name that identifies the function called
1791 * Close all open file handles
1795 public function closeResources() {
1796 array_map( 'fclose', $this->resourcesToClose
);
1801 * FileBackendStore helper function to handle listings that span container shards.
1802 * Do not use this class from places outside of FileBackendStore.
1804 * @ingroup FileBackend
1806 abstract class FileBackendStoreShardListIterator
implements Iterator
{
1807 /** @var FileBackendStore */
1812 protected $shardSuffixes;
1813 protected $container; // string; full container name
1814 protected $directory; // string; resolved relative path
1816 /** @var Traversable */
1818 protected $curShard = 0; // integer
1819 protected $pos = 0; // integer
1822 protected $multiShardPaths = array(); // (rel path => 1)
1825 * @param $backend FileBackendStore
1826 * @param $container string Full storage container name
1827 * @param $dir string Storage directory relative to container
1828 * @param $suffixes Array List of container shard suffixes
1829 * @param $params Array
1831 public function __construct(
1832 FileBackendStore
$backend, $container, $dir, array $suffixes, array $params
1834 $this->backend
= $backend;
1835 $this->container
= $container;
1836 $this->directory
= $dir;
1837 $this->shardSuffixes
= $suffixes;
1838 $this->params
= $params;
1842 * @see Iterator::key()
1845 public function key() {
1850 * @see Iterator::valid()
1853 public function valid() {
1854 if ( $this->iter
instanceof Iterator
) {
1855 return $this->iter
->valid();
1856 } elseif ( is_array( $this->iter
) ) {
1857 return ( current( $this->iter
) !== false ); // no paths can have this value
1859 return false; // some failure?
1863 * @see Iterator::current()
1864 * @return string|bool String or false
1866 public function current() {
1867 return ( $this->iter
instanceof Iterator
)
1868 ?
$this->iter
->current()
1869 : current( $this->iter
);
1873 * @see Iterator::next()
1876 public function next() {
1878 ( $this->iter
instanceof Iterator
) ?
$this->iter
->next() : next( $this->iter
);
1880 $continue = false; // keep scanning shards?
1881 $this->filterViaNext(); // filter out duplicates
1882 // Find the next non-empty shard if no elements are left
1883 if ( !$this->valid() ) {
1884 $this->nextShardIteratorIfNotValid();
1885 $continue = $this->valid(); // re-filter unless we ran out of shards
1887 } while ( $continue );
1891 * @see Iterator::rewind()
1894 public function rewind() {
1896 $this->curShard
= 0;
1897 $this->setIteratorFromCurrentShard();
1899 $continue = false; // keep scanning shards?
1900 $this->filterViaNext(); // filter out duplicates
1901 // Find the next non-empty shard if no elements are left
1902 if ( !$this->valid() ) {
1903 $this->nextShardIteratorIfNotValid();
1904 $continue = $this->valid(); // re-filter unless we ran out of shards
1906 } while ( $continue );
1910 * Filter out duplicate items by advancing to the next ones
1912 protected function filterViaNext() {
1913 while ( $this->valid() ) {
1914 $rel = $this->iter
->current(); // path relative to given directory
1915 $path = $this->params
['dir'] . "/{$rel}"; // full storage path
1916 if ( $this->backend
->isSingleShardPathInternal( $path ) ) {
1917 break; // path is only on one shard; no issue with duplicates
1918 } elseif ( isset( $this->multiShardPaths
[$rel] ) ) {
1919 // Don't keep listing paths that are on multiple shards
1920 ( $this->iter
instanceof Iterator
) ?
$this->iter
->next() : next( $this->iter
);
1922 $this->multiShardPaths
[$rel] = 1;
1929 * If the list iterator for this container shard is out of items,
1930 * then move on to the next container that has items.
1931 * If there are none, then it advances to the last container.
1933 protected function nextShardIteratorIfNotValid() {
1934 while ( !$this->valid() && ++
$this->curShard
< count( $this->shardSuffixes
) ) {
1935 $this->setIteratorFromCurrentShard();
1940 * Set the list iterator to that of the current container shard
1942 protected function setIteratorFromCurrentShard() {
1943 $this->iter
= $this->listFromShard(
1944 $this->container
. $this->shardSuffixes
[$this->curShard
],
1945 $this->directory
, $this->params
);
1946 // Start loading results so that current() works
1947 if ( $this->iter
) {
1948 ( $this->iter
instanceof Iterator
) ?
$this->iter
->rewind() : reset( $this->iter
);
1953 * Get the list for a given container shard
1955 * @param $container string Resolved container name
1956 * @param $dir string Resolved path relative to container
1957 * @param $params Array
1958 * @return Traversable|Array|null
1960 abstract protected function listFromShard( $container, $dir, array $params );
1964 * Iterator for listing directories
1966 class FileBackendStoreShardDirIterator
extends FileBackendStoreShardListIterator
{
1968 * @see FileBackendStoreShardListIterator::listFromShard()
1969 * @return Array|null|Traversable
1971 protected function listFromShard( $container, $dir, array $params ) {
1972 return $this->backend
->getDirectoryListInternal( $container, $dir, $params );
1977 * Iterator for listing regular files
1979 class FileBackendStoreShardFileIterator
extends FileBackendStoreShardListIterator
{
1981 * @see FileBackendStoreShardListIterator::listFromShard()
1982 * @return Array|null|Traversable
1984 protected function listFromShard( $container, $dir, array $params ) {
1985 return $this->backend
->getFileListInternal( $container, $dir, $params );