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::streamFile()
811 final public function streamFile( array $params ) {
812 wfProfileIn( __METHOD__
);
813 wfProfileIn( __METHOD__
. '-' . $this->name
);
814 $status = Status
::newGood();
816 $info = $this->getFileStat( $params );
817 if ( !$info ) { // let StreamFile handle the 404
818 $status->fatal( 'backend-fail-notexists', $params['src'] );
821 // Set output buffer and HTTP headers for stream
822 $extraHeaders = isset( $params['headers'] ) ?
$params['headers'] : array();
823 $res = StreamFile
::prepareForStream( $params['src'], $info, $extraHeaders );
824 if ( $res == StreamFile
::NOT_MODIFIED
) {
825 // do nothing; client cache is up to date
826 } elseif ( $res == StreamFile
::READY_STREAM
) {
827 wfProfileIn( __METHOD__
. '-send' );
828 wfProfileIn( __METHOD__
. '-send-' . $this->name
);
829 $status = $this->doStreamFile( $params );
830 wfProfileOut( __METHOD__
. '-send-' . $this->name
);
831 wfProfileOut( __METHOD__
. '-send' );
832 if ( !$status->isOK() ) {
833 // Per bug 41113, nasty things can happen if bad cache entries get
834 // stuck in cache. It's also possible that this error can come up
835 // with simple race conditions. Clear out the stat cache to be safe.
836 $this->clearCache( array( $params['src'] ) );
837 $this->deleteFileCache( $params['src'] );
838 trigger_error( "Bad stat cache or race condition for file {$params['src']}." );
841 $status->fatal( 'backend-fail-stream', $params['src'] );
844 wfProfileOut( __METHOD__
. '-' . $this->name
);
845 wfProfileOut( __METHOD__
);
850 * @see FileBackendStore::streamFile()
853 protected function doStreamFile( array $params ) {
854 $status = Status
::newGood();
856 $fsFile = $this->getLocalReference( $params );
858 $status->fatal( 'backend-fail-stream', $params['src'] );
859 } elseif ( !readfile( $fsFile->getPath() ) ) {
860 $status->fatal( 'backend-fail-stream', $params['src'] );
867 * @see FileBackend::directoryExists()
870 final public function directoryExists( array $params ) {
871 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
872 if ( $dir === null ) {
873 return false; // invalid storage path
875 if ( $shard !== null ) { // confined to a single container/shard
876 return $this->doDirectoryExists( $fullCont, $dir, $params );
877 } else { // directory is on several shards
878 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
879 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
880 $res = false; // response
881 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
882 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
886 } elseif ( $exists === null ) { // error?
887 $res = null; // if we don't find anything, it is indeterminate
895 * @see FileBackendStore::directoryExists()
897 * @param $container string Resolved container name
898 * @param $dir string Resolved path relative to container
899 * @param $params Array
902 abstract protected function doDirectoryExists( $container, $dir, array $params );
905 * @see FileBackend::getDirectoryList()
906 * @return Traversable|Array|null Returns null on failure
908 final public function getDirectoryList( array $params ) {
909 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
910 if ( $dir === null ) { // invalid storage path
913 if ( $shard !== null ) {
914 // File listing is confined to a single container/shard
915 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
917 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
918 // File listing spans multiple containers/shards
919 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
920 return new FileBackendStoreShardDirIterator( $this,
921 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
926 * Do not call this function from places outside FileBackend
928 * @see FileBackendStore::getDirectoryList()
930 * @param $container string Resolved container name
931 * @param $dir string Resolved path relative to container
932 * @param $params Array
933 * @return Traversable|Array|null Returns null on failure
935 abstract public function getDirectoryListInternal( $container, $dir, array $params );
938 * @see FileBackend::getFileList()
939 * @return Traversable|Array|null Returns null on failure
941 final public function getFileList( array $params ) {
942 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
943 if ( $dir === null ) { // invalid storage path
946 if ( $shard !== null ) {
947 // File listing is confined to a single container/shard
948 return $this->getFileListInternal( $fullCont, $dir, $params );
950 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
951 // File listing spans multiple containers/shards
952 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
953 return new FileBackendStoreShardFileIterator( $this,
954 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
959 * Do not call this function from places outside FileBackend
961 * @see FileBackendStore::getFileList()
963 * @param $container string Resolved container name
964 * @param $dir string Resolved path relative to container
965 * @param $params Array
966 * @return Traversable|Array|null Returns null on failure
968 abstract public function getFileListInternal( $container, $dir, array $params );
971 * Return a list of FileOp objects from a list of operations.
972 * Do not call this function from places outside FileBackend.
974 * The result must have the same number of items as the input.
975 * An exception is thrown if an unsupported operation is requested.
977 * @param $ops Array Same format as doOperations()
978 * @return Array List of FileOp objects
979 * @throws MWException
981 final public function getOperationsInternal( array $ops ) {
982 $supportedOps = array(
983 'store' => 'StoreFileOp',
984 'copy' => 'CopyFileOp',
985 'move' => 'MoveFileOp',
986 'delete' => 'DeleteFileOp',
987 'create' => 'CreateFileOp',
988 'null' => 'NullFileOp'
991 $performOps = array(); // array of FileOp objects
992 // Build up ordered array of FileOps...
993 foreach ( $ops as $operation ) {
994 $opName = $operation['op'];
995 if ( isset( $supportedOps[$opName] ) ) {
996 $class = $supportedOps[$opName];
997 // Get params for this operation
998 $params = $operation;
999 // Append the FileOp class
1000 $performOps[] = new $class( $this, $params );
1002 throw new MWException( "Operation '$opName' is not supported." );
1010 * Get a list of storage paths to lock for a list of operations
1011 * Returns an array with 'sh' (shared) and 'ex' (exclusive) keys,
1012 * each corresponding to a list of storage paths to be locked.
1013 * All returned paths are normalized.
1015 * @param $performOps Array List of FileOp objects
1016 * @return Array ('sh' => list of paths, 'ex' => list of paths)
1018 final public function getPathsToLockForOpsInternal( array $performOps ) {
1019 // Build up a list of files to lock...
1020 $paths = array( 'sh' => array(), 'ex' => array() );
1021 foreach ( $performOps as $fileOp ) {
1022 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1023 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1025 // Optimization: if doing an EX lock anyway, don't also set an SH one
1026 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1027 // Get a shared lock on the parent directory of each path changed
1028 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1034 * @see FileBackend::getScopedLocksForOps()
1037 public function getScopedLocksForOps( array $ops, Status
$status ) {
1038 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1040 $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status ),
1041 $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status )
1046 * @see FileBackend::doOperationsInternal()
1049 final protected function doOperationsInternal( array $ops, array $opts ) {
1050 wfProfileIn( __METHOD__
);
1051 wfProfileIn( __METHOD__
. '-' . $this->name
);
1052 $status = Status
::newGood();
1054 // Build up a list of FileOps...
1055 $performOps = $this->getOperationsInternal( $ops );
1057 // Acquire any locks as needed...
1058 if ( empty( $opts['nonLocking'] ) ) {
1059 // Build up a list of files to lock...
1060 $paths = $this->getPathsToLockForOpsInternal( $performOps );
1061 // Try to lock those files for the scope of this function...
1062 $scopeLockS = $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status );
1063 $scopeLockE = $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status );
1064 if ( !$status->isOK() ) {
1065 wfProfileOut( __METHOD__
. '-' . $this->name
);
1066 wfProfileOut( __METHOD__
);
1067 return $status; // abort
1071 // Clear any file cache entries (after locks acquired)
1072 if ( empty( $opts['preserveCache'] ) ) {
1073 $this->clearCache();
1076 // Load from the persistent file and container caches
1077 $this->primeFileCache( $performOps );
1078 $this->primeContainerCache( $performOps );
1080 // Actually attempt the operation batch...
1081 $opts = $this->setConcurrencyFlags( $opts );
1082 $subStatus = FileOpBatch
::attempt( $performOps, $opts, $this->fileJournal
);
1084 // Merge errors into status fields
1085 $status->merge( $subStatus );
1086 $status->success
= $subStatus->success
; // not done in merge()
1088 wfProfileOut( __METHOD__
. '-' . $this->name
);
1089 wfProfileOut( __METHOD__
);
1094 * @see FileBackend::doQuickOperationsInternal()
1096 * @throws MWException
1098 final protected function doQuickOperationsInternal( array $ops ) {
1099 wfProfileIn( __METHOD__
);
1100 wfProfileIn( __METHOD__
. '-' . $this->name
);
1101 $status = Status
::newGood();
1103 $supportedOps = array( 'create', 'store', 'copy', 'move', 'delete', 'null' );
1104 $async = ( $this->parallelize
=== 'implicit' );
1105 $maxConcurrency = $this->concurrency
; // throttle
1107 $statuses = array(); // array of (index => Status)
1108 $fileOpHandles = array(); // list of (index => handle) arrays
1109 $curFileOpHandles = array(); // current handle batch
1110 // Perform the sync-only ops and build up op handles for the async ops...
1111 foreach ( $ops as $index => $params ) {
1112 if ( !in_array( $params['op'], $supportedOps ) ) {
1113 wfProfileOut( __METHOD__
. '-' . $this->name
);
1114 wfProfileOut( __METHOD__
);
1115 throw new MWException( "Operation '{$params['op']}' is not supported." );
1117 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1118 $subStatus = $this->$method( array( 'async' => $async ) +
$params );
1119 if ( $subStatus->value
instanceof FileBackendStoreOpHandle
) { // async
1120 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1121 $fileOpHandles[] = $curFileOpHandles; // push this batch
1122 $curFileOpHandles = array();
1124 $curFileOpHandles[$index] = $subStatus->value
; // keep index
1125 } else { // error or completed
1126 $statuses[$index] = $subStatus; // keep index
1129 if ( count( $curFileOpHandles ) ) {
1130 $fileOpHandles[] = $curFileOpHandles; // last batch
1132 // Do all the async ops that can be done concurrently...
1133 foreach ( $fileOpHandles as $fileHandleBatch ) {
1134 $statuses = $statuses +
$this->executeOpHandlesInternal( $fileHandleBatch );
1136 // Marshall and merge all the responses...
1137 foreach ( $statuses as $index => $subStatus ) {
1138 $status->merge( $subStatus );
1139 if ( $subStatus->isOK() ) {
1140 $status->success
[$index] = true;
1141 ++
$status->successCount
;
1143 $status->success
[$index] = false;
1144 ++
$status->failCount
;
1148 wfProfileOut( __METHOD__
. '-' . $this->name
);
1149 wfProfileOut( __METHOD__
);
1154 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1155 * The resulting Status object fields will correspond
1156 * to the order in which the handles where given.
1158 * @param $handles Array List of FileBackendStoreOpHandle objects
1159 * @return Array Map of Status objects
1160 * @throws MWException
1162 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1163 wfProfileIn( __METHOD__
);
1164 wfProfileIn( __METHOD__
. '-' . $this->name
);
1165 foreach ( $fileOpHandles as $fileOpHandle ) {
1166 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle
) ) {
1167 throw new MWException( "Given a non-FileBackendStoreOpHandle object." );
1168 } elseif ( $fileOpHandle->backend
->getName() !== $this->getName() ) {
1169 throw new MWException( "Given a FileBackendStoreOpHandle for the wrong backend." );
1172 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1173 foreach ( $fileOpHandles as $fileOpHandle ) {
1174 $fileOpHandle->closeResources();
1176 wfProfileOut( __METHOD__
. '-' . $this->name
);
1177 wfProfileOut( __METHOD__
);
1182 * @see FileBackendStore::executeOpHandlesInternal()
1183 * @param array $fileOpHandles
1184 * @throws MWException
1185 * @return Array List of corresponding Status objects
1187 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1188 foreach ( $fileOpHandles as $fileOpHandle ) { // OK if empty
1189 throw new MWException( "This backend supports no asynchronous operations." );
1195 * @see FileBackend::preloadCache()
1197 final public function preloadCache( array $paths ) {
1198 $fullConts = array(); // full container names
1199 foreach ( $paths as $path ) {
1200 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1201 $fullConts[] = $fullCont;
1203 // Load from the persistent file and container caches
1204 $this->primeContainerCache( $fullConts );
1205 $this->primeFileCache( $paths );
1209 * @see FileBackend::clearCache()
1211 final public function clearCache( array $paths = null ) {
1212 if ( is_array( $paths ) ) {
1213 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1214 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1216 if ( $paths === null ) {
1217 $this->cheapCache
->clear();
1218 $this->expensiveCache
->clear();
1220 foreach ( $paths as $path ) {
1221 $this->cheapCache
->clear( $path );
1222 $this->expensiveCache
->clear( $path );
1225 $this->doClearCache( $paths );
1229 * Clears any additional stat caches for storage paths
1231 * @see FileBackend::clearCache()
1233 * @param $paths Array Storage paths (optional)
1236 protected function doClearCache( array $paths = null ) {}
1239 * Is this a key/value store where directories are just virtual?
1240 * Virtual directories exists in so much as files exists that are
1241 * prefixed with the directory path followed by a forward slash.
1245 abstract protected function directoriesAreVirtual();
1248 * Check if a container name is valid.
1249 * This checks for for length and illegal characters.
1251 * @param $container string
1254 final protected static function isValidContainerName( $container ) {
1255 // This accounts for Swift and S3 restrictions while leaving room
1256 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1257 // This disallows directory separators or traversal characters.
1258 // Note that matching strings URL encode to the same string;
1259 // in Swift, the length restriction is *after* URL encoding.
1260 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1264 * Splits a storage path into an internal container name,
1265 * an internal relative file name, and a container shard suffix.
1266 * Any shard suffix is already appended to the internal container name.
1267 * This also checks that the storage path is valid and within this backend.
1269 * If the container is sharded but a suffix could not be determined,
1270 * this means that the path can only refer to a directory and can only
1271 * be scanned by looking in all the container shards.
1273 * @param $storagePath string
1274 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1276 final protected function resolveStoragePath( $storagePath ) {
1277 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1278 if ( $backend === $this->name
) { // must be for this backend
1279 $relPath = self
::normalizeContainerPath( $relPath );
1280 if ( $relPath !== null ) {
1281 // Get shard for the normalized path if this container is sharded
1282 $cShard = $this->getContainerShard( $container, $relPath );
1283 // Validate and sanitize the relative path (backend-specific)
1284 $relPath = $this->resolveContainerPath( $container, $relPath );
1285 if ( $relPath !== null ) {
1286 // Prepend any wiki ID prefix to the container name
1287 $container = $this->fullContainerName( $container );
1288 if ( self
::isValidContainerName( $container ) ) {
1289 // Validate and sanitize the container name (backend-specific)
1290 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1291 if ( $container !== null ) {
1292 return array( $container, $relPath, $cShard );
1298 return array( null, null, null );
1302 * Like resolveStoragePath() except null values are returned if
1303 * the container is sharded and the shard could not be determined.
1305 * @see FileBackendStore::resolveStoragePath()
1307 * @param $storagePath string
1308 * @return Array (container, path) or (null, null) if invalid
1310 final protected function resolveStoragePathReal( $storagePath ) {
1311 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1312 if ( $cShard !== null ) {
1313 return array( $container, $relPath );
1315 return array( null, null );
1319 * Get the container name shard suffix for a given path.
1320 * Any empty suffix means the container is not sharded.
1322 * @param $container string Container name
1323 * @param $relPath string Storage path relative to the container
1324 * @return string|null Returns null if shard could not be determined
1326 final protected function getContainerShard( $container, $relPath ) {
1327 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1328 if ( $levels == 1 ||
$levels == 2 ) {
1329 // Hash characters are either base 16 or 36
1330 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1331 // Get a regex that represents the shard portion of paths.
1332 // The concatenation of the captures gives us the shard.
1333 if ( $levels === 1 ) { // 16 or 36 shards per container
1334 $hashDirRegex = '(' . $char . ')';
1335 } else { // 256 or 1296 shards per container
1336 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1337 $hashDirRegex = $char . '/(' . $char . '{2})';
1338 } else { // short hash dir format (e.g. "a/b/c")
1339 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1342 // Allow certain directories to be above the hash dirs so as
1343 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1344 // They must be 2+ chars to avoid any hash directory ambiguity.
1346 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1347 return '.' . implode( '', array_slice( $m, 1 ) );
1349 return null; // failed to match
1351 return ''; // no sharding
1355 * Check if a storage path maps to a single shard.
1356 * Container dirs like "a", where the container shards on "x/xy",
1357 * can reside on several shards. Such paths are tricky to handle.
1359 * @param $storagePath string Storage path
1362 final public function isSingleShardPathInternal( $storagePath ) {
1363 list( $c, $r, $shard ) = $this->resolveStoragePath( $storagePath );
1364 return ( $shard !== null );
1368 * Get the sharding config for a container.
1369 * If greater than 0, then all file storage paths within
1370 * the container are required to be hashed accordingly.
1372 * @param $container string
1373 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
1375 final protected function getContainerHashLevels( $container ) {
1376 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1377 $config = $this->shardViaHashLevels
[$container];
1378 $hashLevels = (int)$config['levels'];
1379 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1380 $hashBase = (int)$config['base'];
1381 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1382 return array( $hashLevels, $hashBase, $config['repeat'] );
1386 return array( 0, 0, false ); // no sharding
1390 * Get a list of full container shard suffixes for a container
1392 * @param $container string
1395 final protected function getContainerSuffixes( $container ) {
1397 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1398 if ( $digits > 0 ) {
1399 $numShards = pow( $base, $digits );
1400 for ( $index = 0; $index < $numShards; $index++
) {
1401 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1408 * Get the full container name, including the wiki ID prefix
1410 * @param $container string
1413 final protected function fullContainerName( $container ) {
1414 if ( $this->wikiId
!= '' ) {
1415 return "{$this->wikiId}-$container";
1422 * Resolve a container name, checking if it's allowed by the backend.
1423 * This is intended for internal use, such as encoding illegal chars.
1424 * Subclasses can override this to be more restrictive.
1426 * @param $container string
1427 * @return string|null
1429 protected function resolveContainerName( $container ) {
1434 * Resolve a relative storage path, checking if it's allowed by the backend.
1435 * This is intended for internal use, such as encoding illegal chars or perhaps
1436 * getting absolute paths (e.g. FS based backends). Note that the relative path
1437 * may be the empty string (e.g. the path is simply to the container).
1439 * @param $container string Container name
1440 * @param $relStoragePath string Storage path relative to the container
1441 * @return string|null Path or null if not valid
1443 protected function resolveContainerPath( $container, $relStoragePath ) {
1444 return $relStoragePath;
1448 * Get the cache key for a container
1450 * @param $container string Resolved container name
1453 private function containerCacheKey( $container ) {
1454 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1458 * Set the cached info for a container
1460 * @param $container string Resolved container name
1461 * @param $val mixed Information to cache
1463 final protected function setContainerCache( $container, $val ) {
1464 $this->memCache
->add( $this->containerCacheKey( $container ), $val, 14*86400 );
1468 * Delete the cached info for a container.
1469 * The cache key is salted for a while to prevent race conditions.
1471 * @param $container string Resolved container name
1473 final protected function deleteContainerCache( $container ) {
1474 if ( !$this->memCache
->set( $this->containerCacheKey( $container ), 'PURGED', 300 ) ) {
1475 trigger_error( "Unable to delete stat cache for container $container." );
1480 * Do a batch lookup from cache for container stats for all containers
1481 * used in a list of container names, storage paths, or FileOp objects.
1482 * This loads the persistent cache values into the process cache.
1484 * @param $items Array
1487 final protected function primeContainerCache( array $items ) {
1488 wfProfileIn( __METHOD__
);
1489 wfProfileIn( __METHOD__
. '-' . $this->name
);
1491 $paths = array(); // list of storage paths
1492 $contNames = array(); // (cache key => resolved container name)
1493 // Get all the paths/containers from the items...
1494 foreach ( $items as $item ) {
1495 if ( $item instanceof FileOp
) {
1496 $paths = array_merge( $paths, $item->storagePathsRead() );
1497 $paths = array_merge( $paths, $item->storagePathsChanged() );
1498 } elseif ( self
::isStoragePath( $item ) ) {
1500 } elseif ( is_string( $item ) ) { // full container name
1501 $contNames[$this->containerCacheKey( $item )] = $item;
1504 // Get all the corresponding cache keys for paths...
1505 foreach ( $paths as $path ) {
1506 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1507 if ( $fullCont !== null ) { // valid path for this backend
1508 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1512 $contInfo = array(); // (resolved container name => cache value)
1513 // Get all cache entries for these container cache keys...
1514 $values = $this->memCache
->getMulti( array_keys( $contNames ) );
1515 foreach ( $values as $cacheKey => $val ) {
1516 $contInfo[$contNames[$cacheKey]] = $val;
1519 // Populate the container process cache for the backend...
1520 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1522 wfProfileOut( __METHOD__
. '-' . $this->name
);
1523 wfProfileOut( __METHOD__
);
1527 * Fill the backend-specific process cache given an array of
1528 * resolved container names and their corresponding cached info.
1529 * Only containers that actually exist should appear in the map.
1531 * @param $containerInfo Array Map of resolved container names to cached info
1534 protected function doPrimeContainerCache( array $containerInfo ) {}
1537 * Get the cache key for a file path
1539 * @param $path string Normalized storage path
1542 private function fileCacheKey( $path ) {
1543 return wfMemcKey( 'backend', $this->getName(), 'file', sha1( $path ) );
1547 * Set the cached stat info for a file path.
1548 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1549 * salting for the case when a file is created at a path were there was none before.
1551 * @param $path string Storage path
1552 * @param $val mixed Information to cache
1554 final protected function setFileCache( $path, $val ) {
1555 $path = FileBackend
::normalizeStoragePath( $path );
1556 if ( $path === null ) {
1557 return; // invalid storage path
1559 $this->memCache
->add( $this->fileCacheKey( $path ), $val, 7*86400 );
1563 * Delete the cached stat info for a file path.
1564 * The cache key is salted for a while to prevent race conditions.
1566 * @param $path string Storage path
1568 final protected function deleteFileCache( $path ) {
1569 $path = FileBackend
::normalizeStoragePath( $path );
1570 if ( $path === null ) {
1571 return; // invalid storage path
1573 if ( !$this->memCache
->set( $this->fileCacheKey( $path ), 'PURGED', 300 ) ) {
1574 trigger_error( "Unable to delete stat cache for file $path." );
1579 * Do a batch lookup from cache for file stats for all paths
1580 * used in a list of storage paths or FileOp objects.
1581 * This loads the persistent cache values into the process cache.
1583 * @param $items Array List of storage paths or FileOps
1586 final protected function primeFileCache( array $items ) {
1587 wfProfileIn( __METHOD__
);
1588 wfProfileIn( __METHOD__
. '-' . $this->name
);
1590 $paths = array(); // list of storage paths
1591 $pathNames = array(); // (cache key => storage path)
1592 // Get all the paths/containers from the items...
1593 foreach ( $items as $item ) {
1594 if ( $item instanceof FileOp
) {
1595 $paths = array_merge( $paths, $item->storagePathsRead() );
1596 $paths = array_merge( $paths, $item->storagePathsChanged() );
1597 } elseif ( self
::isStoragePath( $item ) ) {
1598 $paths[] = FileBackend
::normalizeStoragePath( $item );
1601 // Get rid of any paths that failed normalization...
1602 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1603 // Get all the corresponding cache keys for paths...
1604 foreach ( $paths as $path ) {
1605 list( $cont, $rel, $s ) = $this->resolveStoragePath( $path );
1606 if ( $rel !== null ) { // valid path for this backend
1607 $pathNames[$this->fileCacheKey( $path )] = $path;
1610 // Get all cache entries for these container cache keys...
1611 $values = $this->memCache
->getMulti( array_keys( $pathNames ) );
1612 foreach ( $values as $cacheKey => $val ) {
1613 if ( is_array( $val ) ) {
1614 $path = $pathNames[$cacheKey];
1615 $this->cheapCache
->set( $path, 'stat', $val );
1616 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1617 $this->cheapCache
->set( $path, 'sha1',
1618 array( 'hash' => $val['sha1'], 'latest' => $val['latest'] ) );
1623 wfProfileOut( __METHOD__
. '-' . $this->name
);
1624 wfProfileOut( __METHOD__
);
1628 * Set the 'concurrency' option from a list of operation options
1630 * @param $opts array Map of operation options
1633 final protected function setConcurrencyFlags( array $opts ) {
1634 $opts['concurrency'] = 1; // off
1635 if ( $this->parallelize
=== 'implicit' ) {
1636 if ( !isset( $opts['parallelize'] ) ||
$opts['parallelize'] ) {
1637 $opts['concurrency'] = $this->concurrency
;
1639 } elseif ( $this->parallelize
=== 'explicit' ) {
1640 if ( !empty( $opts['parallelize'] ) ) {
1641 $opts['concurrency'] = $this->concurrency
;
1649 * FileBackendStore helper class for performing asynchronous file operations.
1651 * For example, calling FileBackendStore::createInternal() with the "async"
1652 * param flag may result in a Status that contains this object as a value.
1653 * This class is largely backend-specific and is mostly just "magic" to be
1654 * passed to FileBackendStore::executeOpHandlesInternal().
1656 abstract class FileBackendStoreOpHandle
{
1658 public $params = array(); // params to caller functions
1659 /** @var FileBackendStore */
1662 public $resourcesToClose = array();
1664 public $call; // string; name that identifies the function called
1667 * Close all open file handles
1671 public function closeResources() {
1672 array_map( 'fclose', $this->resourcesToClose
);
1677 * FileBackendStore helper function to handle listings that span container shards.
1678 * Do not use this class from places outside of FileBackendStore.
1680 * @ingroup FileBackend
1682 abstract class FileBackendStoreShardListIterator
implements Iterator
{
1683 /** @var FileBackendStore */
1688 protected $shardSuffixes;
1689 protected $container; // string; full container name
1690 protected $directory; // string; resolved relative path
1692 /** @var Traversable */
1694 protected $curShard = 0; // integer
1695 protected $pos = 0; // integer
1698 protected $multiShardPaths = array(); // (rel path => 1)
1701 * @param $backend FileBackendStore
1702 * @param $container string Full storage container name
1703 * @param $dir string Storage directory relative to container
1704 * @param $suffixes Array List of container shard suffixes
1705 * @param $params Array
1707 public function __construct(
1708 FileBackendStore
$backend, $container, $dir, array $suffixes, array $params
1710 $this->backend
= $backend;
1711 $this->container
= $container;
1712 $this->directory
= $dir;
1713 $this->shardSuffixes
= $suffixes;
1714 $this->params
= $params;
1718 * @see Iterator::key()
1721 public function key() {
1726 * @see Iterator::valid()
1729 public function valid() {
1730 if ( $this->iter
instanceof Iterator
) {
1731 return $this->iter
->valid();
1732 } elseif ( is_array( $this->iter
) ) {
1733 return ( current( $this->iter
) !== false ); // no paths can have this value
1735 return false; // some failure?
1739 * @see Iterator::current()
1740 * @return string|bool String or false
1742 public function current() {
1743 return ( $this->iter
instanceof Iterator
)
1744 ?
$this->iter
->current()
1745 : current( $this->iter
);
1749 * @see Iterator::next()
1752 public function next() {
1754 ( $this->iter
instanceof Iterator
) ?
$this->iter
->next() : next( $this->iter
);
1756 $continue = false; // keep scanning shards?
1757 $this->filterViaNext(); // filter out duplicates
1758 // Find the next non-empty shard if no elements are left
1759 if ( !$this->valid() ) {
1760 $this->nextShardIteratorIfNotValid();
1761 $continue = $this->valid(); // re-filter unless we ran out of shards
1763 } while ( $continue );
1767 * @see Iterator::rewind()
1770 public function rewind() {
1772 $this->curShard
= 0;
1773 $this->setIteratorFromCurrentShard();
1775 $continue = false; // keep scanning shards?
1776 $this->filterViaNext(); // filter out duplicates
1777 // Find the next non-empty shard if no elements are left
1778 if ( !$this->valid() ) {
1779 $this->nextShardIteratorIfNotValid();
1780 $continue = $this->valid(); // re-filter unless we ran out of shards
1782 } while ( $continue );
1786 * Filter out duplicate items by advancing to the next ones
1788 protected function filterViaNext() {
1789 while ( $this->valid() ) {
1790 $rel = $this->iter
->current(); // path relative to given directory
1791 $path = $this->params
['dir'] . "/{$rel}"; // full storage path
1792 if ( $this->backend
->isSingleShardPathInternal( $path ) ) {
1793 break; // path is only on one shard; no issue with duplicates
1794 } elseif ( isset( $this->multiShardPaths
[$rel] ) ) {
1795 // Don't keep listing paths that are on multiple shards
1796 ( $this->iter
instanceof Iterator
) ?
$this->iter
->next() : next( $this->iter
);
1798 $this->multiShardPaths
[$rel] = 1;
1805 * If the list iterator for this container shard is out of items,
1806 * then move on to the next container that has items.
1807 * If there are none, then it advances to the last container.
1809 protected function nextShardIteratorIfNotValid() {
1810 while ( !$this->valid() && ++
$this->curShard
< count( $this->shardSuffixes
) ) {
1811 $this->setIteratorFromCurrentShard();
1816 * Set the list iterator to that of the current container shard
1818 protected function setIteratorFromCurrentShard() {
1819 $this->iter
= $this->listFromShard(
1820 $this->container
. $this->shardSuffixes
[$this->curShard
],
1821 $this->directory
, $this->params
);
1822 // Start loading results so that current() works
1823 if ( $this->iter
) {
1824 ( $this->iter
instanceof Iterator
) ?
$this->iter
->rewind() : reset( $this->iter
);
1829 * Get the list for a given container shard
1831 * @param $container string Resolved container name
1832 * @param $dir string Resolved path relative to container
1833 * @param $params Array
1834 * @return Traversable|Array|null
1836 abstract protected function listFromShard( $container, $dir, array $params );
1840 * Iterator for listing directories
1842 class FileBackendStoreShardDirIterator
extends FileBackendStoreShardListIterator
{
1844 * @see FileBackendStoreShardListIterator::listFromShard()
1845 * @return Array|null|Traversable
1847 protected function listFromShard( $container, $dir, array $params ) {
1848 return $this->backend
->getDirectoryListInternal( $container, $dir, $params );
1853 * Iterator for listing regular files
1855 class FileBackendStoreShardFileIterator
extends FileBackendStoreShardListIterator
{
1857 * @see FileBackendStoreShardListIterator::listFromShard()
1858 * @return Array|null|Traversable
1860 protected function listFromShard( $container, $dir, array $params ) {
1861 return $this->backend
->getFileListInternal( $container, $dir, $params );