3 * Base class for all backends using particular storage medium.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup FileBackend
22 * @author Aaron Schulz
26 * @brief Base class for all backends using particular storage medium.
28 * This class defines the methods as abstract that subclasses must implement.
29 * Outside callers should *not* use functions with "Internal" in the name.
31 * The FileBackend operations are implemented using basic functions
32 * such as storeInternal(), copyInternal(), deleteInternal() and the like.
33 * This class is also responsible for path resolution and sanitization.
35 * @ingroup FileBackend
38 abstract class FileBackendStore
extends FileBackend
{
41 /** @var ProcessCacheLRU */
42 protected $cheapCache; // Map of paths to small (RAM/disk) cache items
43 /** @var ProcessCacheLRU */
44 protected $expensiveCache; // Map of paths to large (RAM/disk) cache items
46 /** @var Array Map of container names to sharding settings */
47 protected $shardViaHashLevels = array(); // (container name => config array)
49 protected $maxFileSize = 4294967296; // integer bytes (4GiB)
52 * @see FileBackend::__construct()
54 * @param $config Array
56 public function __construct( array $config ) {
57 parent
::__construct( $config );
58 $this->memCache
= new EmptyBagOStuff(); // disabled by default
59 $this->cheapCache
= new ProcessCacheLRU( 300 );
60 $this->expensiveCache
= new ProcessCacheLRU( 5 );
64 * Get the maximum allowable file size given backend
65 * medium restrictions and basic performance constraints.
66 * Do not call this function from places outside FileBackend and FileOp.
68 * @return integer Bytes
70 final public function maxFileSizeInternal() {
71 return $this->maxFileSize
;
75 * Check if a file can be created or changed at a given storage path.
76 * FS backends should check if the parent directory exists, files can be
77 * written under it, and that any file already there is writable.
78 * Backends using key/value stores should check if the container exists.
80 * @param $storagePath string
83 abstract public function isPathUsableInternal( $storagePath );
86 * Create a file in the backend with the given contents.
87 * This will overwrite any file that exists at the destination.
88 * Do not call this function from places outside FileBackend and FileOp.
91 * - content : the raw file contents
92 * - dst : destination storage path
93 * - disposition : Content-Disposition header value for the destination
94 * - async : Status will be returned immediately if supported.
95 * If the status is OK, then its value field will be
96 * set to a FileBackendStoreOpHandle object.
98 * @param $params Array
101 final public function createInternal( array $params ) {
102 wfProfileIn( __METHOD__
);
103 wfProfileIn( __METHOD__
. '-' . $this->name
);
104 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
105 $status = Status
::newFatal( 'backend-fail-maxsize',
106 $params['dst'], $this->maxFileSizeInternal() );
108 $status = $this->doCreateInternal( $params );
109 $this->clearCache( array( $params['dst'] ) );
110 $this->deleteFileCache( $params['dst'] ); // persistent cache
112 wfProfileOut( __METHOD__
. '-' . $this->name
);
113 wfProfileOut( __METHOD__
);
118 * @see FileBackendStore::createInternal()
120 abstract protected function doCreateInternal( array $params );
123 * Store a file into the backend from a file on disk.
124 * This will overwrite any file that exists at the destination.
125 * Do not call this function from places outside FileBackend and FileOp.
128 * - src : source path on disk
129 * - dst : destination storage path
130 * - disposition : Content-Disposition header value for the destination
131 * - async : Status will be returned immediately if supported.
132 * If the status is OK, then its value field will be
133 * set to a FileBackendStoreOpHandle object.
135 * @param $params Array
138 final public function storeInternal( array $params ) {
139 wfProfileIn( __METHOD__
);
140 wfProfileIn( __METHOD__
. '-' . $this->name
);
141 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
142 $status = Status
::newFatal( 'backend-fail-maxsize',
143 $params['dst'], $this->maxFileSizeInternal() );
145 $status = $this->doStoreInternal( $params );
146 $this->clearCache( array( $params['dst'] ) );
147 $this->deleteFileCache( $params['dst'] ); // persistent cache
149 wfProfileOut( __METHOD__
. '-' . $this->name
);
150 wfProfileOut( __METHOD__
);
155 * @see FileBackendStore::storeInternal()
157 abstract protected function doStoreInternal( array $params );
160 * Copy a file from one storage path to another in the backend.
161 * This will overwrite any file that exists at the destination.
162 * Do not call this function from places outside FileBackend and FileOp.
165 * - src : source storage path
166 * - dst : destination storage path
167 * - ignoreMissingSource : do nothing if the source file does not exist
168 * - disposition : Content-Disposition header value for the destination
169 * - async : Status will be returned immediately if supported.
170 * If the status is OK, then its value field will be
171 * set to a FileBackendStoreOpHandle object.
173 * @param $params Array
176 final public function copyInternal( array $params ) {
177 wfProfileIn( __METHOD__
);
178 wfProfileIn( __METHOD__
. '-' . $this->name
);
179 $status = $this->doCopyInternal( $params );
180 $this->clearCache( array( $params['dst'] ) );
181 $this->deleteFileCache( $params['dst'] ); // persistent cache
182 wfProfileOut( __METHOD__
. '-' . $this->name
);
183 wfProfileOut( __METHOD__
);
188 * @see FileBackendStore::copyInternal()
190 abstract protected function doCopyInternal( array $params );
193 * Delete a file at the storage path.
194 * Do not call this function from places outside FileBackend and FileOp.
197 * - src : source storage path
198 * - ignoreMissingSource : do nothing if the source file does not exist
199 * - async : Status will be returned immediately if supported.
200 * If the status is OK, then its value field will be
201 * set to a FileBackendStoreOpHandle object.
203 * @param $params Array
206 final public function deleteInternal( array $params ) {
207 wfProfileIn( __METHOD__
);
208 wfProfileIn( __METHOD__
. '-' . $this->name
);
209 $status = $this->doDeleteInternal( $params );
210 $this->clearCache( array( $params['src'] ) );
211 $this->deleteFileCache( $params['src'] ); // persistent cache
212 wfProfileOut( __METHOD__
. '-' . $this->name
);
213 wfProfileOut( __METHOD__
);
218 * @see FileBackendStore::deleteInternal()
220 abstract protected function doDeleteInternal( array $params );
223 * Move a file from one storage path to another in the backend.
224 * This will overwrite any file that exists at the destination.
225 * Do not call this function from places outside FileBackend and FileOp.
228 * - src : source storage path
229 * - dst : destination storage path
230 * - ignoreMissingSource : do nothing if the source file does not exist
231 * - disposition : Content-Disposition header value for the destination
232 * - async : Status will be returned immediately if supported.
233 * If the status is OK, then its value field will be
234 * set to a FileBackendStoreOpHandle object.
236 * @param $params Array
239 final public function moveInternal( array $params ) {
240 wfProfileIn( __METHOD__
);
241 wfProfileIn( __METHOD__
. '-' . $this->name
);
242 $status = $this->doMoveInternal( $params );
243 $this->clearCache( array( $params['src'], $params['dst'] ) );
244 $this->deleteFileCache( $params['src'] ); // persistent cache
245 $this->deleteFileCache( $params['dst'] ); // persistent cache
246 wfProfileOut( __METHOD__
. '-' . $this->name
);
247 wfProfileOut( __METHOD__
);
252 * @see FileBackendStore::moveInternal()
255 protected function doMoveInternal( array $params ) {
256 unset( $params['async'] ); // two steps, won't work here :)
257 // Copy source to dest
258 $status = $this->copyInternal( $params );
259 if ( $status->isOK() ) {
260 // Delete source (only fails due to races or medium going down)
261 $status->merge( $this->deleteInternal( array( 'src' => $params['src'] ) ) );
262 $status->setResult( true, $status->value
); // ignore delete() errors
268 * No-op file operation that does nothing.
269 * Do not call this function from places outside FileBackend and FileOp.
271 * @param $params Array
274 final public function nullInternal( array $params ) {
275 return Status
::newGood();
279 * @see FileBackend::concatenate()
282 final public function concatenate( array $params ) {
283 wfProfileIn( __METHOD__
);
284 wfProfileIn( __METHOD__
. '-' . $this->name
);
285 $status = Status
::newGood();
287 // Try to lock the source files for the scope of this function
288 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager
::LOCK_UW
, $status );
289 if ( $status->isOK() ) {
290 // Actually do the file concatenation...
291 $start_time = microtime( true );
292 $status->merge( $this->doConcatenate( $params ) );
293 $sec = microtime( true ) - $start_time;
294 if ( !$status->isOK() ) {
295 wfDebugLog( 'FileOperation', get_class( $this ) . " failed to concatenate " .
296 count( $params['srcs'] ) . " file(s) [$sec sec]" );
300 wfProfileOut( __METHOD__
. '-' . $this->name
);
301 wfProfileOut( __METHOD__
);
306 * @see FileBackendStore::concatenate()
309 protected function doConcatenate( array $params ) {
310 $status = Status
::newGood();
311 $tmpPath = $params['dst']; // convenience
312 unset( $params['latest'] ); // sanity
314 // Check that the specified temp file is valid...
315 wfSuppressWarnings();
316 $ok = ( is_file( $tmpPath ) && filesize( $tmpPath ) == 0 );
318 if ( !$ok ) { // not present or not empty
319 $status->fatal( 'backend-fail-opentemp', $tmpPath );
323 // Get local FS versions of the chunks needed for the concatenation...
324 $fsFiles = $this->getLocalReferenceMulti( $params );
325 foreach ( $fsFiles as $path => &$fsFile ) {
326 if ( !$fsFile ) { // chunk failed to download?
327 $fsFile = $this->getLocalReference( array( 'src' => $path ) );
328 if ( !$fsFile ) { // retry failed?
329 $status->fatal( 'backend-fail-read', $path );
334 unset( $fsFile ); // unset reference so we can reuse $fsFile
336 // Get a handle for the destination temp file
337 $tmpHandle = fopen( $tmpPath, 'ab' );
338 if ( $tmpHandle === false ) {
339 $status->fatal( 'backend-fail-opentemp', $tmpPath );
343 // Build up the temp file using the source chunks (in order)...
344 foreach ( $fsFiles as $virtualSource => $fsFile ) {
345 // Get a handle to the local FS version
346 $sourceHandle = fopen( $fsFile->getPath(), 'rb' );
347 if ( $sourceHandle === false ) {
348 fclose( $tmpHandle );
349 $status->fatal( 'backend-fail-read', $virtualSource );
352 // Append chunk to file (pass chunk size to avoid magic quotes)
353 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
354 fclose( $sourceHandle );
355 fclose( $tmpHandle );
356 $status->fatal( 'backend-fail-writetemp', $tmpPath );
359 fclose( $sourceHandle );
361 if ( !fclose( $tmpHandle ) ) {
362 $status->fatal( 'backend-fail-closetemp', $tmpPath );
366 clearstatcache(); // temp file changed
372 * @see FileBackend::doPrepare()
375 final protected function doPrepare( array $params ) {
376 wfProfileIn( __METHOD__
);
377 wfProfileIn( __METHOD__
. '-' . $this->name
);
379 $status = Status
::newGood();
380 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
381 if ( $dir === null ) {
382 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
383 wfProfileOut( __METHOD__
. '-' . $this->name
);
384 wfProfileOut( __METHOD__
);
385 return $status; // invalid storage path
388 if ( $shard !== null ) { // confined to a single container/shard
389 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
390 } else { // directory is on several shards
391 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
392 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
393 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
394 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
398 wfProfileOut( __METHOD__
. '-' . $this->name
);
399 wfProfileOut( __METHOD__
);
404 * @see FileBackendStore::doPrepare()
407 protected function doPrepareInternal( $container, $dir, array $params ) {
408 return Status
::newGood();
412 * @see FileBackend::doSecure()
415 final protected function doSecure( array $params ) {
416 wfProfileIn( __METHOD__
);
417 wfProfileIn( __METHOD__
. '-' . $this->name
);
418 $status = Status
::newGood();
420 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
421 if ( $dir === null ) {
422 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
423 wfProfileOut( __METHOD__
. '-' . $this->name
);
424 wfProfileOut( __METHOD__
);
425 return $status; // invalid storage path
428 if ( $shard !== null ) { // confined to a single container/shard
429 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
430 } else { // directory is on several shards
431 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
432 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
433 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
434 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
438 wfProfileOut( __METHOD__
. '-' . $this->name
);
439 wfProfileOut( __METHOD__
);
444 * @see FileBackendStore::doSecure()
447 protected function doSecureInternal( $container, $dir, array $params ) {
448 return Status
::newGood();
452 * @see FileBackend::doPublish()
455 final protected function doPublish( array $params ) {
456 wfProfileIn( __METHOD__
);
457 wfProfileIn( __METHOD__
. '-' . $this->name
);
458 $status = Status
::newGood();
460 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
461 if ( $dir === null ) {
462 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
463 wfProfileOut( __METHOD__
. '-' . $this->name
);
464 wfProfileOut( __METHOD__
);
465 return $status; // invalid storage path
468 if ( $shard !== null ) { // confined to a single container/shard
469 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
470 } else { // directory is on several shards
471 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
472 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
473 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
474 $status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
478 wfProfileOut( __METHOD__
. '-' . $this->name
);
479 wfProfileOut( __METHOD__
);
484 * @see FileBackendStore::doPublish()
487 protected function doPublishInternal( $container, $dir, array $params ) {
488 return Status
::newGood();
492 * @see FileBackend::doClean()
495 final protected function doClean( array $params ) {
496 wfProfileIn( __METHOD__
);
497 wfProfileIn( __METHOD__
. '-' . $this->name
);
498 $status = Status
::newGood();
500 // Recursive: first delete all empty subdirs recursively
501 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
502 $subDirsRel = $this->getTopDirectoryList( array( 'dir' => $params['dir'] ) );
503 if ( $subDirsRel !== null ) { // no errors
504 foreach ( $subDirsRel as $subDirRel ) {
505 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
506 $status->merge( $this->doClean( array( 'dir' => $subDir ) +
$params ) );
511 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
512 if ( $dir === null ) {
513 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
514 wfProfileOut( __METHOD__
. '-' . $this->name
);
515 wfProfileOut( __METHOD__
);
516 return $status; // invalid storage path
519 // Attempt to lock this directory...
520 $filesLockEx = array( $params['dir'] );
521 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
522 if ( !$status->isOK() ) {
523 wfProfileOut( __METHOD__
. '-' . $this->name
);
524 wfProfileOut( __METHOD__
);
525 return $status; // abort
528 if ( $shard !== null ) { // confined to a single container/shard
529 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
530 $this->deleteContainerCache( $fullCont ); // purge cache
531 } else { // directory is on several shards
532 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
533 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
534 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
535 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
536 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
540 wfProfileOut( __METHOD__
. '-' . $this->name
);
541 wfProfileOut( __METHOD__
);
546 * @see FileBackendStore::doClean()
549 protected function doCleanInternal( $container, $dir, array $params ) {
550 return Status
::newGood();
554 * @see FileBackend::fileExists()
557 final public function fileExists( array $params ) {
558 wfProfileIn( __METHOD__
);
559 wfProfileIn( __METHOD__
. '-' . $this->name
);
560 $stat = $this->getFileStat( $params );
561 wfProfileOut( __METHOD__
. '-' . $this->name
);
562 wfProfileOut( __METHOD__
);
563 return ( $stat === null ) ?
null : (bool)$stat; // null => failure
567 * @see FileBackend::getFileTimestamp()
570 final public function getFileTimestamp( array $params ) {
571 wfProfileIn( __METHOD__
);
572 wfProfileIn( __METHOD__
. '-' . $this->name
);
573 $stat = $this->getFileStat( $params );
574 wfProfileOut( __METHOD__
. '-' . $this->name
);
575 wfProfileOut( __METHOD__
);
576 return $stat ?
$stat['mtime'] : false;
580 * @see FileBackend::getFileSize()
583 final public function getFileSize( array $params ) {
584 wfProfileIn( __METHOD__
);
585 wfProfileIn( __METHOD__
. '-' . $this->name
);
586 $stat = $this->getFileStat( $params );
587 wfProfileOut( __METHOD__
. '-' . $this->name
);
588 wfProfileOut( __METHOD__
);
589 return $stat ?
$stat['size'] : false;
593 * @see FileBackend::getFileStat()
596 final public function getFileStat( array $params ) {
597 $path = self
::normalizeStoragePath( $params['src'] );
598 if ( $path === null ) {
599 return false; // invalid storage path
601 wfProfileIn( __METHOD__
);
602 wfProfileIn( __METHOD__
. '-' . $this->name
);
603 $latest = !empty( $params['latest'] ); // use latest data?
604 if ( !$this->cheapCache
->has( $path, 'stat' ) ) {
605 $this->primeFileCache( array( $path ) ); // check persistent cache
607 if ( $this->cheapCache
->has( $path, 'stat' ) ) {
608 $stat = $this->cheapCache
->get( $path, 'stat' );
609 // If we want the latest data, check that this cached
610 // value was in fact fetched with the latest available data.
611 if ( !$latest ||
$stat['latest'] ) {
612 wfProfileOut( __METHOD__
. '-' . $this->name
);
613 wfProfileOut( __METHOD__
);
617 wfProfileIn( __METHOD__
. '-miss' );
618 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
619 $stat = $this->doGetFileStat( $params );
620 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
621 wfProfileOut( __METHOD__
. '-miss' );
622 if ( is_array( $stat ) ) { // don't cache negatives
623 $stat['latest'] = $latest;
624 $this->cheapCache
->set( $path, 'stat', $stat );
625 $this->setFileCache( $path, $stat ); // update persistent cache
626 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
627 $this->cheapCache
->set( $path, 'sha1',
628 array( 'hash' => $stat['sha1'], 'latest' => $latest ) );
631 wfDebug( __METHOD__
. ": File $path does not exist.\n" );
633 wfProfileOut( __METHOD__
. '-' . $this->name
);
634 wfProfileOut( __METHOD__
);
639 * @see FileBackendStore::getFileStat()
641 abstract protected function doGetFileStat( array $params );
644 * @see FileBackend::getFileContentsMulti()
647 public function getFileContentsMulti( array $params ) {
648 wfProfileIn( __METHOD__
);
649 wfProfileIn( __METHOD__
. '-' . $this->name
);
651 $params = $this->setConcurrencyFlags( $params );
652 $contents = $this->doGetFileContentsMulti( $params );
654 wfProfileOut( __METHOD__
. '-' . $this->name
);
655 wfProfileOut( __METHOD__
);
660 * @see FileBackendStore::getFileContentsMulti()
663 protected function doGetFileContentsMulti( array $params ) {
665 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
666 wfSuppressWarnings();
667 $contents[$path] = $fsFile ?
file_get_contents( $fsFile->getPath() ) : false;
674 * @see FileBackend::getFileSha1Base36()
675 * @return bool|string
677 final public function getFileSha1Base36( array $params ) {
678 $path = self
::normalizeStoragePath( $params['src'] );
679 if ( $path === null ) {
680 return false; // invalid storage path
682 wfProfileIn( __METHOD__
);
683 wfProfileIn( __METHOD__
. '-' . $this->name
);
684 $latest = !empty( $params['latest'] ); // use latest data?
685 if ( $this->cheapCache
->has( $path, 'sha1' ) ) {
686 $stat = $this->cheapCache
->get( $path, 'sha1' );
687 // If we want the latest data, check that this cached
688 // value was in fact fetched with the latest available data.
689 if ( !$latest ||
$stat['latest'] ) {
690 wfProfileOut( __METHOD__
. '-' . $this->name
);
691 wfProfileOut( __METHOD__
);
692 return $stat['hash'];
695 wfProfileIn( __METHOD__
. '-miss' );
696 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
697 $hash = $this->doGetFileSha1Base36( $params );
698 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
699 wfProfileOut( __METHOD__
. '-miss' );
700 if ( $hash ) { // don't cache negatives
701 $this->cheapCache
->set( $path, 'sha1',
702 array( 'hash' => $hash, 'latest' => $latest ) );
704 wfProfileOut( __METHOD__
. '-' . $this->name
);
705 wfProfileOut( __METHOD__
);
710 * @see FileBackendStore::getFileSha1Base36()
711 * @return bool|string
713 protected function doGetFileSha1Base36( array $params ) {
714 $fsFile = $this->getLocalReference( $params );
718 return $fsFile->getSha1Base36();
723 * @see FileBackend::getFileProps()
726 final public function getFileProps( array $params ) {
727 wfProfileIn( __METHOD__
);
728 wfProfileIn( __METHOD__
. '-' . $this->name
);
729 $fsFile = $this->getLocalReference( $params );
730 $props = $fsFile ?
$fsFile->getProps() : FSFile
::placeholderProps();
731 wfProfileOut( __METHOD__
. '-' . $this->name
);
732 wfProfileOut( __METHOD__
);
737 * @see FileBackend::getLocalReferenceMulti()
740 final public function getLocalReferenceMulti( array $params ) {
741 wfProfileIn( __METHOD__
);
742 wfProfileIn( __METHOD__
. '-' . $this->name
);
744 $params = $this->setConcurrencyFlags( $params );
746 $fsFiles = array(); // (path => FSFile)
747 $latest = !empty( $params['latest'] ); // use latest data?
748 // Reuse any files already in process cache...
749 foreach ( $params['srcs'] as $src ) {
750 $path = self
::normalizeStoragePath( $src );
751 if ( $path === null ) {
752 $fsFiles[$src] = null; // invalid storage path
753 } elseif ( $this->expensiveCache
->has( $path, 'localRef' ) ) {
754 $val = $this->expensiveCache
->get( $path, 'localRef' );
755 // If we want the latest data, check that this cached
756 // value was in fact fetched with the latest available data.
757 if ( !$latest ||
$val['latest'] ) {
758 $fsFiles[$src] = $val['object'];
762 // Fetch local references of any remaning files...
763 $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
764 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
765 $fsFiles[$path] = $fsFile;
766 if ( $fsFile ) { // update the process cache...
767 $this->expensiveCache
->set( $path, 'localRef',
768 array( 'object' => $fsFile, 'latest' => $latest ) );
772 wfProfileOut( __METHOD__
. '-' . $this->name
);
773 wfProfileOut( __METHOD__
);
778 * @see FileBackendStore::getLocalReferenceMulti()
781 protected function doGetLocalReferenceMulti( array $params ) {
782 return $this->doGetLocalCopyMulti( $params );
786 * @see FileBackend::getLocalCopyMulti()
789 final public function getLocalCopyMulti( array $params ) {
790 wfProfileIn( __METHOD__
);
791 wfProfileIn( __METHOD__
. '-' . $this->name
);
793 $params = $this->setConcurrencyFlags( $params );
794 $tmpFiles = $this->doGetLocalCopyMulti( $params );
796 wfProfileOut( __METHOD__
. '-' . $this->name
);
797 wfProfileOut( __METHOD__
);
802 * @see FileBackendStore::getLocalCopyMulti()
805 abstract protected function doGetLocalCopyMulti( array $params );
808 * @see FileBackend::getFileHttpUrl()
809 * @return string|null
811 public function getFileHttpUrl( array $params ) {
812 return null; // not supported
816 * @see FileBackend::streamFile()
819 final public function streamFile( array $params ) {
820 wfProfileIn( __METHOD__
);
821 wfProfileIn( __METHOD__
. '-' . $this->name
);
822 $status = Status
::newGood();
824 $info = $this->getFileStat( $params );
825 if ( !$info ) { // let StreamFile handle the 404
826 $status->fatal( 'backend-fail-notexists', $params['src'] );
829 // Set output buffer and HTTP headers for stream
830 $extraHeaders = isset( $params['headers'] ) ?
$params['headers'] : array();
831 $res = StreamFile
::prepareForStream( $params['src'], $info, $extraHeaders );
832 if ( $res == StreamFile
::NOT_MODIFIED
) {
833 // do nothing; client cache is up to date
834 } elseif ( $res == StreamFile
::READY_STREAM
) {
835 wfProfileIn( __METHOD__
. '-send' );
836 wfProfileIn( __METHOD__
. '-send-' . $this->name
);
837 $status = $this->doStreamFile( $params );
838 wfProfileOut( __METHOD__
. '-send-' . $this->name
);
839 wfProfileOut( __METHOD__
. '-send' );
840 if ( !$status->isOK() ) {
841 // Per bug 41113, nasty things can happen if bad cache entries get
842 // stuck in cache. It's also possible that this error can come up
843 // with simple race conditions. Clear out the stat cache to be safe.
844 $this->clearCache( array( $params['src'] ) );
845 $this->deleteFileCache( $params['src'] );
846 trigger_error( "Bad stat cache or race condition for file {$params['src']}." );
849 $status->fatal( 'backend-fail-stream', $params['src'] );
852 wfProfileOut( __METHOD__
. '-' . $this->name
);
853 wfProfileOut( __METHOD__
);
858 * @see FileBackendStore::streamFile()
861 protected function doStreamFile( array $params ) {
862 $status = Status
::newGood();
864 $fsFile = $this->getLocalReference( $params );
866 $status->fatal( 'backend-fail-stream', $params['src'] );
867 } elseif ( !readfile( $fsFile->getPath() ) ) {
868 $status->fatal( 'backend-fail-stream', $params['src'] );
875 * @see FileBackend::directoryExists()
878 final public function directoryExists( array $params ) {
879 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
880 if ( $dir === null ) {
881 return false; // invalid storage path
883 if ( $shard !== null ) { // confined to a single container/shard
884 return $this->doDirectoryExists( $fullCont, $dir, $params );
885 } else { // directory is on several shards
886 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
887 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
888 $res = false; // response
889 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
890 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
894 } elseif ( $exists === null ) { // error?
895 $res = null; // if we don't find anything, it is indeterminate
903 * @see FileBackendStore::directoryExists()
905 * @param $container string Resolved container name
906 * @param $dir string Resolved path relative to container
907 * @param $params Array
910 abstract protected function doDirectoryExists( $container, $dir, array $params );
913 * @see FileBackend::getDirectoryList()
914 * @return Traversable|Array|null Returns null on failure
916 final public function getDirectoryList( array $params ) {
917 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
918 if ( $dir === null ) { // invalid storage path
921 if ( $shard !== null ) {
922 // File listing is confined to a single container/shard
923 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
925 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
926 // File listing spans multiple containers/shards
927 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
928 return new FileBackendStoreShardDirIterator( $this,
929 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
934 * Do not call this function from places outside FileBackend
936 * @see FileBackendStore::getDirectoryList()
938 * @param $container string Resolved container name
939 * @param $dir string Resolved path relative to container
940 * @param $params Array
941 * @return Traversable|Array|null Returns null on failure
943 abstract public function getDirectoryListInternal( $container, $dir, array $params );
946 * @see FileBackend::getFileList()
947 * @return Traversable|Array|null Returns null on failure
949 final public function getFileList( array $params ) {
950 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
951 if ( $dir === null ) { // invalid storage path
954 if ( $shard !== null ) {
955 // File listing is confined to a single container/shard
956 return $this->getFileListInternal( $fullCont, $dir, $params );
958 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
959 // File listing spans multiple containers/shards
960 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
961 return new FileBackendStoreShardFileIterator( $this,
962 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
967 * Do not call this function from places outside FileBackend
969 * @see FileBackendStore::getFileList()
971 * @param $container string Resolved container name
972 * @param $dir string Resolved path relative to container
973 * @param $params Array
974 * @return Traversable|Array|null Returns null on failure
976 abstract public function getFileListInternal( $container, $dir, array $params );
979 * Return a list of FileOp objects from a list of operations.
980 * Do not call this function from places outside FileBackend.
982 * The result must have the same number of items as the input.
983 * An exception is thrown if an unsupported operation is requested.
985 * @param $ops Array Same format as doOperations()
986 * @return Array List of FileOp objects
987 * @throws MWException
989 final public function getOperationsInternal( array $ops ) {
990 $supportedOps = array(
991 'store' => 'StoreFileOp',
992 'copy' => 'CopyFileOp',
993 'move' => 'MoveFileOp',
994 'delete' => 'DeleteFileOp',
995 'create' => 'CreateFileOp',
996 'null' => 'NullFileOp'
999 $performOps = array(); // array of FileOp objects
1000 // Build up ordered array of FileOps...
1001 foreach ( $ops as $operation ) {
1002 $opName = $operation['op'];
1003 if ( isset( $supportedOps[$opName] ) ) {
1004 $class = $supportedOps[$opName];
1005 // Get params for this operation
1006 $params = $operation;
1007 // Append the FileOp class
1008 $performOps[] = new $class( $this, $params );
1010 throw new MWException( "Operation '$opName' is not supported." );
1018 * Get a list of storage paths to lock for a list of operations
1019 * Returns an array with 'sh' (shared) and 'ex' (exclusive) keys,
1020 * each corresponding to a list of storage paths to be locked.
1021 * All returned paths are normalized.
1023 * @param $performOps Array List of FileOp objects
1024 * @return Array ('sh' => list of paths, 'ex' => list of paths)
1026 final public function getPathsToLockForOpsInternal( array $performOps ) {
1027 // Build up a list of files to lock...
1028 $paths = array( 'sh' => array(), 'ex' => array() );
1029 foreach ( $performOps as $fileOp ) {
1030 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1031 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1033 // Optimization: if doing an EX lock anyway, don't also set an SH one
1034 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1035 // Get a shared lock on the parent directory of each path changed
1036 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1042 * @see FileBackend::getScopedLocksForOps()
1045 public function getScopedLocksForOps( array $ops, Status
$status ) {
1046 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1048 $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status ),
1049 $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status )
1054 * @see FileBackend::doOperationsInternal()
1057 final protected function doOperationsInternal( array $ops, array $opts ) {
1058 wfProfileIn( __METHOD__
);
1059 wfProfileIn( __METHOD__
. '-' . $this->name
);
1060 $status = Status
::newGood();
1062 // Build up a list of FileOps...
1063 $performOps = $this->getOperationsInternal( $ops );
1065 // Acquire any locks as needed...
1066 if ( empty( $opts['nonLocking'] ) ) {
1067 // Build up a list of files to lock...
1068 $paths = $this->getPathsToLockForOpsInternal( $performOps );
1069 // Try to lock those files for the scope of this function...
1070 $scopeLockS = $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status );
1071 $scopeLockE = $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status );
1072 if ( !$status->isOK() ) {
1073 wfProfileOut( __METHOD__
. '-' . $this->name
);
1074 wfProfileOut( __METHOD__
);
1075 return $status; // abort
1079 // Clear any file cache entries (after locks acquired)
1080 if ( empty( $opts['preserveCache'] ) ) {
1081 $this->clearCache();
1084 // Load from the persistent file and container caches
1085 $this->primeFileCache( $performOps );
1086 $this->primeContainerCache( $performOps );
1088 // Actually attempt the operation batch...
1089 $opts = $this->setConcurrencyFlags( $opts );
1090 $subStatus = FileOpBatch
::attempt( $performOps, $opts, $this->fileJournal
);
1092 // Merge errors into status fields
1093 $status->merge( $subStatus );
1094 $status->success
= $subStatus->success
; // not done in merge()
1096 wfProfileOut( __METHOD__
. '-' . $this->name
);
1097 wfProfileOut( __METHOD__
);
1102 * @see FileBackend::doQuickOperationsInternal()
1104 * @throws MWException
1106 final protected function doQuickOperationsInternal( array $ops ) {
1107 wfProfileIn( __METHOD__
);
1108 wfProfileIn( __METHOD__
. '-' . $this->name
);
1109 $status = Status
::newGood();
1111 $supportedOps = array( 'create', 'store', 'copy', 'move', 'delete', 'null' );
1112 $async = ( $this->parallelize
=== 'implicit' );
1113 $maxConcurrency = $this->concurrency
; // throttle
1115 $statuses = array(); // array of (index => Status)
1116 $fileOpHandles = array(); // list of (index => handle) arrays
1117 $curFileOpHandles = array(); // current handle batch
1118 // Perform the sync-only ops and build up op handles for the async ops...
1119 foreach ( $ops as $index => $params ) {
1120 if ( !in_array( $params['op'], $supportedOps ) ) {
1121 wfProfileOut( __METHOD__
. '-' . $this->name
);
1122 wfProfileOut( __METHOD__
);
1123 throw new MWException( "Operation '{$params['op']}' is not supported." );
1125 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1126 $subStatus = $this->$method( array( 'async' => $async ) +
$params );
1127 if ( $subStatus->value
instanceof FileBackendStoreOpHandle
) { // async
1128 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1129 $fileOpHandles[] = $curFileOpHandles; // push this batch
1130 $curFileOpHandles = array();
1132 $curFileOpHandles[$index] = $subStatus->value
; // keep index
1133 } else { // error or completed
1134 $statuses[$index] = $subStatus; // keep index
1137 if ( count( $curFileOpHandles ) ) {
1138 $fileOpHandles[] = $curFileOpHandles; // last batch
1140 // Do all the async ops that can be done concurrently...
1141 foreach ( $fileOpHandles as $fileHandleBatch ) {
1142 $statuses = $statuses +
$this->executeOpHandlesInternal( $fileHandleBatch );
1144 // Marshall and merge all the responses...
1145 foreach ( $statuses as $index => $subStatus ) {
1146 $status->merge( $subStatus );
1147 if ( $subStatus->isOK() ) {
1148 $status->success
[$index] = true;
1149 ++
$status->successCount
;
1151 $status->success
[$index] = false;
1152 ++
$status->failCount
;
1156 wfProfileOut( __METHOD__
. '-' . $this->name
);
1157 wfProfileOut( __METHOD__
);
1162 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1163 * The resulting Status object fields will correspond
1164 * to the order in which the handles where given.
1166 * @param $handles Array List of FileBackendStoreOpHandle objects
1167 * @return Array Map of Status objects
1168 * @throws MWException
1170 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1171 wfProfileIn( __METHOD__
);
1172 wfProfileIn( __METHOD__
. '-' . $this->name
);
1173 foreach ( $fileOpHandles as $fileOpHandle ) {
1174 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle
) ) {
1175 throw new MWException( "Given a non-FileBackendStoreOpHandle object." );
1176 } elseif ( $fileOpHandle->backend
->getName() !== $this->getName() ) {
1177 throw new MWException( "Given a FileBackendStoreOpHandle for the wrong backend." );
1180 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1181 foreach ( $fileOpHandles as $fileOpHandle ) {
1182 $fileOpHandle->closeResources();
1184 wfProfileOut( __METHOD__
. '-' . $this->name
);
1185 wfProfileOut( __METHOD__
);
1190 * @see FileBackendStore::executeOpHandlesInternal()
1191 * @param array $fileOpHandles
1192 * @throws MWException
1193 * @return Array List of corresponding Status objects
1195 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1196 foreach ( $fileOpHandles as $fileOpHandle ) { // OK if empty
1197 throw new MWException( "This backend supports no asynchronous operations." );
1203 * @see FileBackend::preloadCache()
1205 final public function preloadCache( array $paths ) {
1206 $fullConts = array(); // full container names
1207 foreach ( $paths as $path ) {
1208 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1209 $fullConts[] = $fullCont;
1211 // Load from the persistent file and container caches
1212 $this->primeContainerCache( $fullConts );
1213 $this->primeFileCache( $paths );
1217 * @see FileBackend::clearCache()
1219 final public function clearCache( array $paths = null ) {
1220 if ( is_array( $paths ) ) {
1221 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1222 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1224 if ( $paths === null ) {
1225 $this->cheapCache
->clear();
1226 $this->expensiveCache
->clear();
1228 foreach ( $paths as $path ) {
1229 $this->cheapCache
->clear( $path );
1230 $this->expensiveCache
->clear( $path );
1233 $this->doClearCache( $paths );
1237 * Clears any additional stat caches for storage paths
1239 * @see FileBackend::clearCache()
1241 * @param $paths Array Storage paths (optional)
1244 protected function doClearCache( array $paths = null ) {}
1247 * Is this a key/value store where directories are just virtual?
1248 * Virtual directories exists in so much as files exists that are
1249 * prefixed with the directory path followed by a forward slash.
1253 abstract protected function directoriesAreVirtual();
1256 * Check if a container name is valid.
1257 * This checks for for length and illegal characters.
1259 * @param $container string
1262 final protected static function isValidContainerName( $container ) {
1263 // This accounts for Swift and S3 restrictions while leaving room
1264 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1265 // This disallows directory separators or traversal characters.
1266 // Note that matching strings URL encode to the same string;
1267 // in Swift, the length restriction is *after* URL encoding.
1268 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1272 * Splits a storage path into an internal container name,
1273 * an internal relative file name, and a container shard suffix.
1274 * Any shard suffix is already appended to the internal container name.
1275 * This also checks that the storage path is valid and within this backend.
1277 * If the container is sharded but a suffix could not be determined,
1278 * this means that the path can only refer to a directory and can only
1279 * be scanned by looking in all the container shards.
1281 * @param $storagePath string
1282 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1284 final protected function resolveStoragePath( $storagePath ) {
1285 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1286 if ( $backend === $this->name
) { // must be for this backend
1287 $relPath = self
::normalizeContainerPath( $relPath );
1288 if ( $relPath !== null ) {
1289 // Get shard for the normalized path if this container is sharded
1290 $cShard = $this->getContainerShard( $container, $relPath );
1291 // Validate and sanitize the relative path (backend-specific)
1292 $relPath = $this->resolveContainerPath( $container, $relPath );
1293 if ( $relPath !== null ) {
1294 // Prepend any wiki ID prefix to the container name
1295 $container = $this->fullContainerName( $container );
1296 if ( self
::isValidContainerName( $container ) ) {
1297 // Validate and sanitize the container name (backend-specific)
1298 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1299 if ( $container !== null ) {
1300 return array( $container, $relPath, $cShard );
1306 return array( null, null, null );
1310 * Like resolveStoragePath() except null values are returned if
1311 * the container is sharded and the shard could not be determined.
1313 * @see FileBackendStore::resolveStoragePath()
1315 * @param $storagePath string
1316 * @return Array (container, path) or (null, null) if invalid
1318 final protected function resolveStoragePathReal( $storagePath ) {
1319 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1320 if ( $cShard !== null ) {
1321 return array( $container, $relPath );
1323 return array( null, null );
1327 * Get the container name shard suffix for a given path.
1328 * Any empty suffix means the container is not sharded.
1330 * @param $container string Container name
1331 * @param $relPath string Storage path relative to the container
1332 * @return string|null Returns null if shard could not be determined
1334 final protected function getContainerShard( $container, $relPath ) {
1335 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1336 if ( $levels == 1 ||
$levels == 2 ) {
1337 // Hash characters are either base 16 or 36
1338 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1339 // Get a regex that represents the shard portion of paths.
1340 // The concatenation of the captures gives us the shard.
1341 if ( $levels === 1 ) { // 16 or 36 shards per container
1342 $hashDirRegex = '(' . $char . ')';
1343 } else { // 256 or 1296 shards per container
1344 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1345 $hashDirRegex = $char . '/(' . $char . '{2})';
1346 } else { // short hash dir format (e.g. "a/b/c")
1347 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1350 // Allow certain directories to be above the hash dirs so as
1351 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1352 // They must be 2+ chars to avoid any hash directory ambiguity.
1354 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1355 return '.' . implode( '', array_slice( $m, 1 ) );
1357 return null; // failed to match
1359 return ''; // no sharding
1363 * Check if a storage path maps to a single shard.
1364 * Container dirs like "a", where the container shards on "x/xy",
1365 * can reside on several shards. Such paths are tricky to handle.
1367 * @param $storagePath string Storage path
1370 final public function isSingleShardPathInternal( $storagePath ) {
1371 list( $c, $r, $shard ) = $this->resolveStoragePath( $storagePath );
1372 return ( $shard !== null );
1376 * Get the sharding config for a container.
1377 * If greater than 0, then all file storage paths within
1378 * the container are required to be hashed accordingly.
1380 * @param $container string
1381 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
1383 final protected function getContainerHashLevels( $container ) {
1384 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1385 $config = $this->shardViaHashLevels
[$container];
1386 $hashLevels = (int)$config['levels'];
1387 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1388 $hashBase = (int)$config['base'];
1389 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1390 return array( $hashLevels, $hashBase, $config['repeat'] );
1394 return array( 0, 0, false ); // no sharding
1398 * Get a list of full container shard suffixes for a container
1400 * @param $container string
1403 final protected function getContainerSuffixes( $container ) {
1405 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1406 if ( $digits > 0 ) {
1407 $numShards = pow( $base, $digits );
1408 for ( $index = 0; $index < $numShards; $index++
) {
1409 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1416 * Get the full container name, including the wiki ID prefix
1418 * @param $container string
1421 final protected function fullContainerName( $container ) {
1422 if ( $this->wikiId
!= '' ) {
1423 return "{$this->wikiId}-$container";
1430 * Resolve a container name, checking if it's allowed by the backend.
1431 * This is intended for internal use, such as encoding illegal chars.
1432 * Subclasses can override this to be more restrictive.
1434 * @param $container string
1435 * @return string|null
1437 protected function resolveContainerName( $container ) {
1442 * Resolve a relative storage path, checking if it's allowed by the backend.
1443 * This is intended for internal use, such as encoding illegal chars or perhaps
1444 * getting absolute paths (e.g. FS based backends). Note that the relative path
1445 * may be the empty string (e.g. the path is simply to the container).
1447 * @param $container string Container name
1448 * @param $relStoragePath string Storage path relative to the container
1449 * @return string|null Path or null if not valid
1451 protected function resolveContainerPath( $container, $relStoragePath ) {
1452 return $relStoragePath;
1456 * Get the cache key for a container
1458 * @param $container string Resolved container name
1461 private function containerCacheKey( $container ) {
1462 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1466 * Set the cached info for a container
1468 * @param $container string Resolved container name
1469 * @param $val mixed Information to cache
1471 final protected function setContainerCache( $container, $val ) {
1472 $this->memCache
->add( $this->containerCacheKey( $container ), $val, 14*86400 );
1476 * Delete the cached info for a container.
1477 * The cache key is salted for a while to prevent race conditions.
1479 * @param $container string Resolved container name
1481 final protected function deleteContainerCache( $container ) {
1482 if ( !$this->memCache
->set( $this->containerCacheKey( $container ), 'PURGED', 300 ) ) {
1483 trigger_error( "Unable to delete stat cache for container $container." );
1488 * Do a batch lookup from cache for container stats for all containers
1489 * used in a list of container names, storage paths, or FileOp objects.
1490 * This loads the persistent cache values into the process cache.
1492 * @param $items Array
1495 final protected function primeContainerCache( array $items ) {
1496 wfProfileIn( __METHOD__
);
1497 wfProfileIn( __METHOD__
. '-' . $this->name
);
1499 $paths = array(); // list of storage paths
1500 $contNames = array(); // (cache key => resolved container name)
1501 // Get all the paths/containers from the items...
1502 foreach ( $items as $item ) {
1503 if ( $item instanceof FileOp
) {
1504 $paths = array_merge( $paths, $item->storagePathsRead() );
1505 $paths = array_merge( $paths, $item->storagePathsChanged() );
1506 } elseif ( self
::isStoragePath( $item ) ) {
1508 } elseif ( is_string( $item ) ) { // full container name
1509 $contNames[$this->containerCacheKey( $item )] = $item;
1512 // Get all the corresponding cache keys for paths...
1513 foreach ( $paths as $path ) {
1514 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1515 if ( $fullCont !== null ) { // valid path for this backend
1516 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1520 $contInfo = array(); // (resolved container name => cache value)
1521 // Get all cache entries for these container cache keys...
1522 $values = $this->memCache
->getMulti( array_keys( $contNames ) );
1523 foreach ( $values as $cacheKey => $val ) {
1524 $contInfo[$contNames[$cacheKey]] = $val;
1527 // Populate the container process cache for the backend...
1528 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1530 wfProfileOut( __METHOD__
. '-' . $this->name
);
1531 wfProfileOut( __METHOD__
);
1535 * Fill the backend-specific process cache given an array of
1536 * resolved container names and their corresponding cached info.
1537 * Only containers that actually exist should appear in the map.
1539 * @param $containerInfo Array Map of resolved container names to cached info
1542 protected function doPrimeContainerCache( array $containerInfo ) {}
1545 * Get the cache key for a file path
1547 * @param $path string Normalized storage path
1550 private function fileCacheKey( $path ) {
1551 return wfMemcKey( 'backend', $this->getName(), 'file', sha1( $path ) );
1555 * Set the cached stat info for a file path.
1556 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1557 * salting for the case when a file is created at a path were there was none before.
1559 * @param $path string Storage path
1560 * @param $val mixed Information to cache
1562 final protected function setFileCache( $path, $val ) {
1563 $path = FileBackend
::normalizeStoragePath( $path );
1564 if ( $path === null ) {
1565 return; // invalid storage path
1567 $this->memCache
->add( $this->fileCacheKey( $path ), $val, 7*86400 );
1571 * Delete the cached stat info for a file path.
1572 * The cache key is salted for a while to prevent race conditions.
1574 * @param $path string Storage path
1576 final protected function deleteFileCache( $path ) {
1577 $path = FileBackend
::normalizeStoragePath( $path );
1578 if ( $path === null ) {
1579 return; // invalid storage path
1581 if ( !$this->memCache
->set( $this->fileCacheKey( $path ), 'PURGED', 300 ) ) {
1582 trigger_error( "Unable to delete stat cache for file $path." );
1587 * Do a batch lookup from cache for file stats for all paths
1588 * used in a list of storage paths or FileOp objects.
1589 * This loads the persistent cache values into the process cache.
1591 * @param $items Array List of storage paths or FileOps
1594 final protected function primeFileCache( array $items ) {
1595 wfProfileIn( __METHOD__
);
1596 wfProfileIn( __METHOD__
. '-' . $this->name
);
1598 $paths = array(); // list of storage paths
1599 $pathNames = array(); // (cache key => storage path)
1600 // Get all the paths/containers from the items...
1601 foreach ( $items as $item ) {
1602 if ( $item instanceof FileOp
) {
1603 $paths = array_merge( $paths, $item->storagePathsRead() );
1604 $paths = array_merge( $paths, $item->storagePathsChanged() );
1605 } elseif ( self
::isStoragePath( $item ) ) {
1606 $paths[] = FileBackend
::normalizeStoragePath( $item );
1609 // Get rid of any paths that failed normalization...
1610 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1611 // Get all the corresponding cache keys for paths...
1612 foreach ( $paths as $path ) {
1613 list( $cont, $rel, $s ) = $this->resolveStoragePath( $path );
1614 if ( $rel !== null ) { // valid path for this backend
1615 $pathNames[$this->fileCacheKey( $path )] = $path;
1618 // Get all cache entries for these container cache keys...
1619 $values = $this->memCache
->getMulti( array_keys( $pathNames ) );
1620 foreach ( $values as $cacheKey => $val ) {
1621 if ( is_array( $val ) ) {
1622 $path = $pathNames[$cacheKey];
1623 $this->cheapCache
->set( $path, 'stat', $val );
1624 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1625 $this->cheapCache
->set( $path, 'sha1',
1626 array( 'hash' => $val['sha1'], 'latest' => $val['latest'] ) );
1631 wfProfileOut( __METHOD__
. '-' . $this->name
);
1632 wfProfileOut( __METHOD__
);
1636 * Set the 'concurrency' option from a list of operation options
1638 * @param $opts array Map of operation options
1641 final protected function setConcurrencyFlags( array $opts ) {
1642 $opts['concurrency'] = 1; // off
1643 if ( $this->parallelize
=== 'implicit' ) {
1644 if ( !isset( $opts['parallelize'] ) ||
$opts['parallelize'] ) {
1645 $opts['concurrency'] = $this->concurrency
;
1647 } elseif ( $this->parallelize
=== 'explicit' ) {
1648 if ( !empty( $opts['parallelize'] ) ) {
1649 $opts['concurrency'] = $this->concurrency
;
1657 * FileBackendStore helper class for performing asynchronous file operations.
1659 * For example, calling FileBackendStore::createInternal() with the "async"
1660 * param flag may result in a Status that contains this object as a value.
1661 * This class is largely backend-specific and is mostly just "magic" to be
1662 * passed to FileBackendStore::executeOpHandlesInternal().
1664 abstract class FileBackendStoreOpHandle
{
1666 public $params = array(); // params to caller functions
1667 /** @var FileBackendStore */
1670 public $resourcesToClose = array();
1672 public $call; // string; name that identifies the function called
1675 * Close all open file handles
1679 public function closeResources() {
1680 array_map( 'fclose', $this->resourcesToClose
);
1685 * FileBackendStore helper function to handle listings that span container shards.
1686 * Do not use this class from places outside of FileBackendStore.
1688 * @ingroup FileBackend
1690 abstract class FileBackendStoreShardListIterator
implements Iterator
{
1691 /** @var FileBackendStore */
1696 protected $shardSuffixes;
1697 protected $container; // string; full container name
1698 protected $directory; // string; resolved relative path
1700 /** @var Traversable */
1702 protected $curShard = 0; // integer
1703 protected $pos = 0; // integer
1706 protected $multiShardPaths = array(); // (rel path => 1)
1709 * @param $backend FileBackendStore
1710 * @param $container string Full storage container name
1711 * @param $dir string Storage directory relative to container
1712 * @param $suffixes Array List of container shard suffixes
1713 * @param $params Array
1715 public function __construct(
1716 FileBackendStore
$backend, $container, $dir, array $suffixes, array $params
1718 $this->backend
= $backend;
1719 $this->container
= $container;
1720 $this->directory
= $dir;
1721 $this->shardSuffixes
= $suffixes;
1722 $this->params
= $params;
1726 * @see Iterator::key()
1729 public function key() {
1734 * @see Iterator::valid()
1737 public function valid() {
1738 if ( $this->iter
instanceof Iterator
) {
1739 return $this->iter
->valid();
1740 } elseif ( is_array( $this->iter
) ) {
1741 return ( current( $this->iter
) !== false ); // no paths can have this value
1743 return false; // some failure?
1747 * @see Iterator::current()
1748 * @return string|bool String or false
1750 public function current() {
1751 return ( $this->iter
instanceof Iterator
)
1752 ?
$this->iter
->current()
1753 : current( $this->iter
);
1757 * @see Iterator::next()
1760 public function next() {
1762 ( $this->iter
instanceof Iterator
) ?
$this->iter
->next() : next( $this->iter
);
1764 $continue = false; // keep scanning shards?
1765 $this->filterViaNext(); // filter out duplicates
1766 // Find the next non-empty shard if no elements are left
1767 if ( !$this->valid() ) {
1768 $this->nextShardIteratorIfNotValid();
1769 $continue = $this->valid(); // re-filter unless we ran out of shards
1771 } while ( $continue );
1775 * @see Iterator::rewind()
1778 public function rewind() {
1780 $this->curShard
= 0;
1781 $this->setIteratorFromCurrentShard();
1783 $continue = false; // keep scanning shards?
1784 $this->filterViaNext(); // filter out duplicates
1785 // Find the next non-empty shard if no elements are left
1786 if ( !$this->valid() ) {
1787 $this->nextShardIteratorIfNotValid();
1788 $continue = $this->valid(); // re-filter unless we ran out of shards
1790 } while ( $continue );
1794 * Filter out duplicate items by advancing to the next ones
1796 protected function filterViaNext() {
1797 while ( $this->valid() ) {
1798 $rel = $this->iter
->current(); // path relative to given directory
1799 $path = $this->params
['dir'] . "/{$rel}"; // full storage path
1800 if ( $this->backend
->isSingleShardPathInternal( $path ) ) {
1801 break; // path is only on one shard; no issue with duplicates
1802 } elseif ( isset( $this->multiShardPaths
[$rel] ) ) {
1803 // Don't keep listing paths that are on multiple shards
1804 ( $this->iter
instanceof Iterator
) ?
$this->iter
->next() : next( $this->iter
);
1806 $this->multiShardPaths
[$rel] = 1;
1813 * If the list iterator for this container shard is out of items,
1814 * then move on to the next container that has items.
1815 * If there are none, then it advances to the last container.
1817 protected function nextShardIteratorIfNotValid() {
1818 while ( !$this->valid() && ++
$this->curShard
< count( $this->shardSuffixes
) ) {
1819 $this->setIteratorFromCurrentShard();
1824 * Set the list iterator to that of the current container shard
1826 protected function setIteratorFromCurrentShard() {
1827 $this->iter
= $this->listFromShard(
1828 $this->container
. $this->shardSuffixes
[$this->curShard
],
1829 $this->directory
, $this->params
);
1830 // Start loading results so that current() works
1831 if ( $this->iter
) {
1832 ( $this->iter
instanceof Iterator
) ?
$this->iter
->rewind() : reset( $this->iter
);
1837 * Get the list for a given container shard
1839 * @param $container string Resolved container name
1840 * @param $dir string Resolved path relative to container
1841 * @param $params Array
1842 * @return Traversable|Array|null
1844 abstract protected function listFromShard( $container, $dir, array $params );
1848 * Iterator for listing directories
1850 class FileBackendStoreShardDirIterator
extends FileBackendStoreShardListIterator
{
1852 * @see FileBackendStoreShardListIterator::listFromShard()
1853 * @return Array|null|Traversable
1855 protected function listFromShard( $container, $dir, array $params ) {
1856 return $this->backend
->getDirectoryListInternal( $container, $dir, $params );
1861 * Iterator for listing regular files
1863 class FileBackendStoreShardFileIterator
extends FileBackendStoreShardListIterator
{
1865 * @see FileBackendStoreShardListIterator::listFromShard()
1866 * @return Array|null|Traversable
1868 protected function listFromShard( $container, $dir, array $params ) {
1869 return $this->backend
->getFileListInternal( $container, $dir, $params );