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 at a given storage path.
76 * FS backends should check if the parent directory exists and the file is writable.
77 * Backends using key/value stores should check if the container exists.
79 * @param $storagePath string
82 abstract public function isPathUsableInternal( $storagePath );
85 * Create a file in the backend with the given contents.
86 * This will overwrite any file that exists at the destination.
87 * Do not call this function from places outside FileBackend and FileOp.
90 * - content : the raw file contents
91 * - dst : destination storage path
92 * - disposition : Content-Disposition header value for the destination
93 * - async : Status will be returned immediately if supported.
94 * If the status is OK, then its value field will be
95 * set to a FileBackendStoreOpHandle object.
97 * @param $params Array
100 final public function createInternal( array $params ) {
101 wfProfileIn( __METHOD__
);
102 wfProfileIn( __METHOD__
. '-' . $this->name
);
103 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
104 $status = Status
::newFatal( 'backend-fail-maxsize',
105 $params['dst'], $this->maxFileSizeInternal() );
107 $status = $this->doCreateInternal( $params );
108 $this->clearCache( array( $params['dst'] ) );
109 $this->deleteFileCache( $params['dst'] ); // persistent cache
111 wfProfileOut( __METHOD__
. '-' . $this->name
);
112 wfProfileOut( __METHOD__
);
117 * @see FileBackendStore::createInternal()
119 abstract protected function doCreateInternal( array $params );
122 * Store a file into the backend from a file on disk.
123 * This will overwrite any file that exists at the destination.
124 * Do not call this function from places outside FileBackend and FileOp.
127 * - src : source path on disk
128 * - dst : destination storage path
129 * - disposition : Content-Disposition header value for the destination
130 * - async : Status will be returned immediately if supported.
131 * If the status is OK, then its value field will be
132 * set to a FileBackendStoreOpHandle object.
134 * @param $params Array
137 final public function storeInternal( array $params ) {
138 wfProfileIn( __METHOD__
);
139 wfProfileIn( __METHOD__
. '-' . $this->name
);
140 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
141 $status = Status
::newFatal( 'backend-fail-maxsize',
142 $params['dst'], $this->maxFileSizeInternal() );
144 $status = $this->doStoreInternal( $params );
145 $this->clearCache( array( $params['dst'] ) );
146 $this->deleteFileCache( $params['dst'] ); // persistent cache
148 wfProfileOut( __METHOD__
. '-' . $this->name
);
149 wfProfileOut( __METHOD__
);
154 * @see FileBackendStore::storeInternal()
156 abstract protected function doStoreInternal( array $params );
159 * Copy a file from one storage path to another in the backend.
160 * This will overwrite any file that exists at the destination.
161 * Do not call this function from places outside FileBackend and FileOp.
164 * - src : source storage path
165 * - dst : destination storage path
166 * - disposition : Content-Disposition header value for the destination
167 * - async : Status will be returned immediately if supported.
168 * If the status is OK, then its value field will be
169 * set to a FileBackendStoreOpHandle object.
171 * @param $params Array
174 final public function copyInternal( array $params ) {
175 wfProfileIn( __METHOD__
);
176 wfProfileIn( __METHOD__
. '-' . $this->name
);
177 $status = $this->doCopyInternal( $params );
178 $this->clearCache( array( $params['dst'] ) );
179 $this->deleteFileCache( $params['dst'] ); // persistent cache
180 wfProfileOut( __METHOD__
. '-' . $this->name
);
181 wfProfileOut( __METHOD__
);
186 * @see FileBackendStore::copyInternal()
188 abstract protected function doCopyInternal( array $params );
191 * Delete a file at the storage path.
192 * Do not call this function from places outside FileBackend and FileOp.
195 * - src : source storage path
196 * - ignoreMissingSource : do nothing if the source file does not exist
197 * - async : Status will be returned immediately if supported.
198 * If the status is OK, then its value field will be
199 * set to a FileBackendStoreOpHandle object.
201 * @param $params Array
204 final public function deleteInternal( array $params ) {
205 wfProfileIn( __METHOD__
);
206 wfProfileIn( __METHOD__
. '-' . $this->name
);
207 $status = $this->doDeleteInternal( $params );
208 $this->clearCache( array( $params['src'] ) );
209 $this->deleteFileCache( $params['src'] ); // persistent cache
210 wfProfileOut( __METHOD__
. '-' . $this->name
);
211 wfProfileOut( __METHOD__
);
216 * @see FileBackendStore::deleteInternal()
218 abstract protected function doDeleteInternal( array $params );
221 * Move a file from one storage path to another in the backend.
222 * This will overwrite any file that exists at the destination.
223 * Do not call this function from places outside FileBackend and FileOp.
226 * - src : source storage path
227 * - dst : destination storage path
228 * - disposition : Content-Disposition header value for the destination
229 * - async : Status will be returned immediately if supported.
230 * If the status is OK, then its value field will be
231 * set to a FileBackendStoreOpHandle object.
233 * @param $params Array
236 final public function moveInternal( array $params ) {
237 wfProfileIn( __METHOD__
);
238 wfProfileIn( __METHOD__
. '-' . $this->name
);
239 $status = $this->doMoveInternal( $params );
240 $this->clearCache( array( $params['src'], $params['dst'] ) );
241 $this->deleteFileCache( $params['src'] ); // persistent cache
242 $this->deleteFileCache( $params['dst'] ); // persistent cache
243 wfProfileOut( __METHOD__
. '-' . $this->name
);
244 wfProfileOut( __METHOD__
);
249 * @see FileBackendStore::moveInternal()
252 protected function doMoveInternal( array $params ) {
253 unset( $params['async'] ); // two steps, won't work here :)
254 // Copy source to dest
255 $status = $this->copyInternal( $params );
256 if ( $status->isOK() ) {
257 // Delete source (only fails due to races or medium going down)
258 $status->merge( $this->deleteInternal( array( 'src' => $params['src'] ) ) );
259 $status->setResult( true, $status->value
); // ignore delete() errors
265 * No-op file operation that does nothing.
266 * Do not call this function from places outside FileBackend and FileOp.
268 * @param $params Array
271 final public function nullInternal( array $params ) {
272 return Status
::newGood();
276 * @see FileBackend::concatenate()
279 final public function concatenate( array $params ) {
280 wfProfileIn( __METHOD__
);
281 wfProfileIn( __METHOD__
. '-' . $this->name
);
282 $status = Status
::newGood();
284 // Try to lock the source files for the scope of this function
285 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager
::LOCK_UW
, $status );
286 if ( $status->isOK() ) {
287 // Actually do the file concatenation...
288 $start_time = microtime( true );
289 $status->merge( $this->doConcatenate( $params ) );
290 $sec = microtime( true ) - $start_time;
291 if ( !$status->isOK() ) {
292 wfDebugLog( 'FileOperation', get_class( $this ) . " failed to concatenate " .
293 count( $params['srcs'] ) . " file(s) [$sec sec]" );
297 wfProfileOut( __METHOD__
. '-' . $this->name
);
298 wfProfileOut( __METHOD__
);
303 * @see FileBackendStore::concatenate()
306 protected function doConcatenate( array $params ) {
307 $status = Status
::newGood();
308 $tmpPath = $params['dst']; // convenience
309 unset( $params['latest'] ); // sanity
311 // Check that the specified temp file is valid...
312 wfSuppressWarnings();
313 $ok = ( is_file( $tmpPath ) && filesize( $tmpPath ) == 0 );
315 if ( !$ok ) { // not present or not empty
316 $status->fatal( 'backend-fail-opentemp', $tmpPath );
320 // Get local FS versions of the chunks needed for the concatenation...
321 $fsFiles = $this->getLocalReferenceMulti( $params );
322 foreach ( $fsFiles as $path => &$fsFile ) {
323 if ( !$fsFile ) { // chunk failed to download?
324 $fsFile = $this->getLocalReference( array( 'src' => $path ) );
325 if ( !$fsFile ) { // retry failed?
326 $status->fatal( 'backend-fail-read', $path );
331 unset( $fsFile ); // unset reference so we can reuse $fsFile
333 // Get a handle for the destination temp file
334 $tmpHandle = fopen( $tmpPath, 'ab' );
335 if ( $tmpHandle === false ) {
336 $status->fatal( 'backend-fail-opentemp', $tmpPath );
340 // Build up the temp file using the source chunks (in order)...
341 foreach ( $fsFiles as $virtualSource => $fsFile ) {
342 // Get a handle to the local FS version
343 $sourceHandle = fopen( $fsFile->getPath(), 'rb' );
344 if ( $sourceHandle === false ) {
345 fclose( $tmpHandle );
346 $status->fatal( 'backend-fail-read', $virtualSource );
349 // Append chunk to file (pass chunk size to avoid magic quotes)
350 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
351 fclose( $sourceHandle );
352 fclose( $tmpHandle );
353 $status->fatal( 'backend-fail-writetemp', $tmpPath );
356 fclose( $sourceHandle );
358 if ( !fclose( $tmpHandle ) ) {
359 $status->fatal( 'backend-fail-closetemp', $tmpPath );
363 clearstatcache(); // temp file changed
369 * @see FileBackend::doPrepare()
372 final protected function doPrepare( array $params ) {
373 wfProfileIn( __METHOD__
);
374 wfProfileIn( __METHOD__
. '-' . $this->name
);
376 $status = Status
::newGood();
377 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
378 if ( $dir === null ) {
379 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
380 wfProfileOut( __METHOD__
. '-' . $this->name
);
381 wfProfileOut( __METHOD__
);
382 return $status; // invalid storage path
385 if ( $shard !== null ) { // confined to a single container/shard
386 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
387 } else { // directory is on several shards
388 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
389 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
390 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
391 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
395 wfProfileOut( __METHOD__
. '-' . $this->name
);
396 wfProfileOut( __METHOD__
);
401 * @see FileBackendStore::doPrepare()
404 protected function doPrepareInternal( $container, $dir, array $params ) {
405 return Status
::newGood();
409 * @see FileBackend::doSecure()
412 final protected function doSecure( array $params ) {
413 wfProfileIn( __METHOD__
);
414 wfProfileIn( __METHOD__
. '-' . $this->name
);
415 $status = Status
::newGood();
417 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
418 if ( $dir === null ) {
419 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
420 wfProfileOut( __METHOD__
. '-' . $this->name
);
421 wfProfileOut( __METHOD__
);
422 return $status; // invalid storage path
425 if ( $shard !== null ) { // confined to a single container/shard
426 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
427 } else { // directory is on several shards
428 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
429 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
430 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
431 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
435 wfProfileOut( __METHOD__
. '-' . $this->name
);
436 wfProfileOut( __METHOD__
);
441 * @see FileBackendStore::doSecure()
444 protected function doSecureInternal( $container, $dir, array $params ) {
445 return Status
::newGood();
449 * @see FileBackend::doPublish()
452 final protected function doPublish( array $params ) {
453 wfProfileIn( __METHOD__
);
454 wfProfileIn( __METHOD__
. '-' . $this->name
);
455 $status = Status
::newGood();
457 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
458 if ( $dir === null ) {
459 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
460 wfProfileOut( __METHOD__
. '-' . $this->name
);
461 wfProfileOut( __METHOD__
);
462 return $status; // invalid storage path
465 if ( $shard !== null ) { // confined to a single container/shard
466 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
467 } else { // directory is on several shards
468 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
469 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
470 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
471 $status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
475 wfProfileOut( __METHOD__
. '-' . $this->name
);
476 wfProfileOut( __METHOD__
);
481 * @see FileBackendStore::doPublish()
484 protected function doPublishInternal( $container, $dir, array $params ) {
485 return Status
::newGood();
489 * @see FileBackend::doClean()
492 final protected function doClean( array $params ) {
493 wfProfileIn( __METHOD__
);
494 wfProfileIn( __METHOD__
. '-' . $this->name
);
495 $status = Status
::newGood();
497 // Recursive: first delete all empty subdirs recursively
498 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
499 $subDirsRel = $this->getTopDirectoryList( array( 'dir' => $params['dir'] ) );
500 if ( $subDirsRel !== null ) { // no errors
501 foreach ( $subDirsRel as $subDirRel ) {
502 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
503 $status->merge( $this->doClean( array( 'dir' => $subDir ) +
$params ) );
508 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
509 if ( $dir === null ) {
510 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
511 wfProfileOut( __METHOD__
. '-' . $this->name
);
512 wfProfileOut( __METHOD__
);
513 return $status; // invalid storage path
516 // Attempt to lock this directory...
517 $filesLockEx = array( $params['dir'] );
518 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
519 if ( !$status->isOK() ) {
520 wfProfileOut( __METHOD__
. '-' . $this->name
);
521 wfProfileOut( __METHOD__
);
522 return $status; // abort
525 if ( $shard !== null ) { // confined to a single container/shard
526 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
527 $this->deleteContainerCache( $fullCont ); // purge cache
528 } else { // directory is on several shards
529 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
530 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
531 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
532 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
533 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
537 wfProfileOut( __METHOD__
. '-' . $this->name
);
538 wfProfileOut( __METHOD__
);
543 * @see FileBackendStore::doClean()
546 protected function doCleanInternal( $container, $dir, array $params ) {
547 return Status
::newGood();
551 * @see FileBackend::fileExists()
554 final public function fileExists( array $params ) {
555 wfProfileIn( __METHOD__
);
556 wfProfileIn( __METHOD__
. '-' . $this->name
);
557 $stat = $this->getFileStat( $params );
558 wfProfileOut( __METHOD__
. '-' . $this->name
);
559 wfProfileOut( __METHOD__
);
560 return ( $stat === null ) ?
null : (bool)$stat; // null => failure
564 * @see FileBackend::getFileTimestamp()
567 final public function getFileTimestamp( array $params ) {
568 wfProfileIn( __METHOD__
);
569 wfProfileIn( __METHOD__
. '-' . $this->name
);
570 $stat = $this->getFileStat( $params );
571 wfProfileOut( __METHOD__
. '-' . $this->name
);
572 wfProfileOut( __METHOD__
);
573 return $stat ?
$stat['mtime'] : false;
577 * @see FileBackend::getFileSize()
580 final public function getFileSize( array $params ) {
581 wfProfileIn( __METHOD__
);
582 wfProfileIn( __METHOD__
. '-' . $this->name
);
583 $stat = $this->getFileStat( $params );
584 wfProfileOut( __METHOD__
. '-' . $this->name
);
585 wfProfileOut( __METHOD__
);
586 return $stat ?
$stat['size'] : false;
590 * @see FileBackend::getFileStat()
593 final public function getFileStat( array $params ) {
594 $path = self
::normalizeStoragePath( $params['src'] );
595 if ( $path === null ) {
596 return false; // invalid storage path
598 wfProfileIn( __METHOD__
);
599 wfProfileIn( __METHOD__
. '-' . $this->name
);
600 $latest = !empty( $params['latest'] ); // use latest data?
601 if ( !$this->cheapCache
->has( $path, 'stat' ) ) {
602 $this->primeFileCache( array( $path ) ); // check persistent cache
604 if ( $this->cheapCache
->has( $path, 'stat' ) ) {
605 $stat = $this->cheapCache
->get( $path, 'stat' );
606 // If we want the latest data, check that this cached
607 // value was in fact fetched with the latest available data.
608 if ( !$latest ||
$stat['latest'] ) {
609 wfProfileOut( __METHOD__
. '-' . $this->name
);
610 wfProfileOut( __METHOD__
);
614 wfProfileIn( __METHOD__
. '-miss' );
615 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
616 $stat = $this->doGetFileStat( $params );
617 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
618 wfProfileOut( __METHOD__
. '-miss' );
619 if ( is_array( $stat ) ) { // don't cache negatives
620 $stat['latest'] = $latest;
621 $this->cheapCache
->set( $path, 'stat', $stat );
622 $this->setFileCache( $path, $stat ); // update persistent cache
623 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
624 $this->cheapCache
->set( $path, 'sha1',
625 array( 'hash' => $stat['sha1'], 'latest' => $latest ) );
628 wfDebug( __METHOD__
. ": File $path does not exist.\n" );
630 wfProfileOut( __METHOD__
. '-' . $this->name
);
631 wfProfileOut( __METHOD__
);
636 * @see FileBackendStore::getFileStat()
638 abstract protected function doGetFileStat( array $params );
641 * @see FileBackend::getFileContentsMulti()
644 public function getFileContentsMulti( array $params ) {
645 wfProfileIn( __METHOD__
);
646 wfProfileIn( __METHOD__
. '-' . $this->name
);
648 $params = $this->setConcurrencyFlags( $params );
649 $contents = $this->doGetFileContentsMulti( $params );
651 wfProfileOut( __METHOD__
. '-' . $this->name
);
652 wfProfileOut( __METHOD__
);
657 * @see FileBackendStore::getFileContentsMulti()
660 protected function doGetFileContentsMulti( array $params ) {
662 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
663 wfSuppressWarnings();
664 $contents[$path] = $fsFile ?
file_get_contents( $fsFile->getPath() ) : false;
671 * @see FileBackend::getFileSha1Base36()
672 * @return bool|string
674 final public function getFileSha1Base36( array $params ) {
675 $path = self
::normalizeStoragePath( $params['src'] );
676 if ( $path === null ) {
677 return false; // invalid storage path
679 wfProfileIn( __METHOD__
);
680 wfProfileIn( __METHOD__
. '-' . $this->name
);
681 $latest = !empty( $params['latest'] ); // use latest data?
682 if ( $this->cheapCache
->has( $path, 'sha1' ) ) {
683 $stat = $this->cheapCache
->get( $path, 'sha1' );
684 // If we want the latest data, check that this cached
685 // value was in fact fetched with the latest available data.
686 if ( !$latest ||
$stat['latest'] ) {
687 wfProfileOut( __METHOD__
. '-' . $this->name
);
688 wfProfileOut( __METHOD__
);
689 return $stat['hash'];
692 wfProfileIn( __METHOD__
. '-miss' );
693 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
694 $hash = $this->doGetFileSha1Base36( $params );
695 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
696 wfProfileOut( __METHOD__
. '-miss' );
697 if ( $hash ) { // don't cache negatives
698 $this->cheapCache
->set( $path, 'sha1',
699 array( 'hash' => $hash, 'latest' => $latest ) );
701 wfProfileOut( __METHOD__
. '-' . $this->name
);
702 wfProfileOut( __METHOD__
);
707 * @see FileBackendStore::getFileSha1Base36()
708 * @return bool|string
710 protected function doGetFileSha1Base36( array $params ) {
711 $fsFile = $this->getLocalReference( $params );
715 return $fsFile->getSha1Base36();
720 * @see FileBackend::getFileProps()
723 final public function getFileProps( array $params ) {
724 wfProfileIn( __METHOD__
);
725 wfProfileIn( __METHOD__
. '-' . $this->name
);
726 $fsFile = $this->getLocalReference( $params );
727 $props = $fsFile ?
$fsFile->getProps() : FSFile
::placeholderProps();
728 wfProfileOut( __METHOD__
. '-' . $this->name
);
729 wfProfileOut( __METHOD__
);
734 * @see FileBackend::getLocalReferenceMulti()
737 final public function getLocalReferenceMulti( array $params ) {
738 wfProfileIn( __METHOD__
);
739 wfProfileIn( __METHOD__
. '-' . $this->name
);
741 $params = $this->setConcurrencyFlags( $params );
743 $fsFiles = array(); // (path => FSFile)
744 $latest = !empty( $params['latest'] ); // use latest data?
745 // Reuse any files already in process cache...
746 foreach ( $params['srcs'] as $src ) {
747 $path = self
::normalizeStoragePath( $src );
748 if ( $path === null ) {
749 $fsFiles[$src] = null; // invalid storage path
750 } elseif ( $this->expensiveCache
->has( $path, 'localRef' ) ) {
751 $val = $this->expensiveCache
->get( $path, 'localRef' );
752 // If we want the latest data, check that this cached
753 // value was in fact fetched with the latest available data.
754 if ( !$latest ||
$val['latest'] ) {
755 $fsFiles[$src] = $val['object'];
759 // Fetch local references of any remaning files...
760 $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
761 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
762 $fsFiles[$path] = $fsFile;
763 if ( $fsFile ) { // update the process cache...
764 $this->expensiveCache
->set( $path, 'localRef',
765 array( 'object' => $fsFile, 'latest' => $latest ) );
769 wfProfileOut( __METHOD__
. '-' . $this->name
);
770 wfProfileOut( __METHOD__
);
775 * @see FileBackendStore::getLocalReferenceMulti()
778 protected function doGetLocalReferenceMulti( array $params ) {
779 return $this->doGetLocalCopyMulti( $params );
783 * @see FileBackend::getLocalCopyMulti()
786 final public function getLocalCopyMulti( array $params ) {
787 wfProfileIn( __METHOD__
);
788 wfProfileIn( __METHOD__
. '-' . $this->name
);
790 $params = $this->setConcurrencyFlags( $params );
791 $tmpFiles = $this->doGetLocalCopyMulti( $params );
793 wfProfileOut( __METHOD__
. '-' . $this->name
);
794 wfProfileOut( __METHOD__
);
799 * @see FileBackendStore::getLocalCopyMulti()
802 abstract protected function doGetLocalCopyMulti( array $params );
805 * @see FileBackend::streamFile()
808 final public function streamFile( array $params ) {
809 wfProfileIn( __METHOD__
);
810 wfProfileIn( __METHOD__
. '-' . $this->name
);
811 $status = Status
::newGood();
813 $info = $this->getFileStat( $params );
814 if ( !$info ) { // let StreamFile handle the 404
815 $status->fatal( 'backend-fail-notexists', $params['src'] );
818 // Set output buffer and HTTP headers for stream
819 $extraHeaders = isset( $params['headers'] ) ?
$params['headers'] : array();
820 $res = StreamFile
::prepareForStream( $params['src'], $info, $extraHeaders );
821 if ( $res == StreamFile
::NOT_MODIFIED
) {
822 // do nothing; client cache is up to date
823 } elseif ( $res == StreamFile
::READY_STREAM
) {
824 wfProfileIn( __METHOD__
. '-send' );
825 wfProfileIn( __METHOD__
. '-send-' . $this->name
);
826 $status = $this->doStreamFile( $params );
827 wfProfileOut( __METHOD__
. '-send-' . $this->name
);
828 wfProfileOut( __METHOD__
. '-send' );
829 if ( !$status->isOK() ) {
830 // Per bug 41113, nasty things can happen if bad cache entries get
831 // stuck in cache. It's also possible that this error can come up
832 // with simple race conditions. Clear out the stat cache to be safe.
833 $this->clearCache( array( $params['src'] ) );
834 $this->deleteFileCache( $params['src'] );
835 trigger_error( "Bad stat cache or race condition for file {$params['src']}." );
838 $status->fatal( 'backend-fail-stream', $params['src'] );
841 wfProfileOut( __METHOD__
. '-' . $this->name
);
842 wfProfileOut( __METHOD__
);
847 * @see FileBackendStore::streamFile()
850 protected function doStreamFile( array $params ) {
851 $status = Status
::newGood();
853 $fsFile = $this->getLocalReference( $params );
855 $status->fatal( 'backend-fail-stream', $params['src'] );
856 } elseif ( !readfile( $fsFile->getPath() ) ) {
857 $status->fatal( 'backend-fail-stream', $params['src'] );
864 * @see FileBackend::directoryExists()
867 final public function directoryExists( array $params ) {
868 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
869 if ( $dir === null ) {
870 return false; // invalid storage path
872 if ( $shard !== null ) { // confined to a single container/shard
873 return $this->doDirectoryExists( $fullCont, $dir, $params );
874 } else { // directory is on several shards
875 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
876 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
877 $res = false; // response
878 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
879 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
883 } elseif ( $exists === null ) { // error?
884 $res = null; // if we don't find anything, it is indeterminate
892 * @see FileBackendStore::directoryExists()
894 * @param $container string Resolved container name
895 * @param $dir string Resolved path relative to container
896 * @param $params Array
899 abstract protected function doDirectoryExists( $container, $dir, array $params );
902 * @see FileBackend::getDirectoryList()
903 * @return Traversable|Array|null Returns null on failure
905 final public function getDirectoryList( array $params ) {
906 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
907 if ( $dir === null ) { // invalid storage path
910 if ( $shard !== null ) {
911 // File listing is confined to a single container/shard
912 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
914 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
915 // File listing spans multiple containers/shards
916 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
917 return new FileBackendStoreShardDirIterator( $this,
918 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
923 * Do not call this function from places outside FileBackend
925 * @see FileBackendStore::getDirectoryList()
927 * @param $container string Resolved container name
928 * @param $dir string Resolved path relative to container
929 * @param $params Array
930 * @return Traversable|Array|null Returns null on failure
932 abstract public function getDirectoryListInternal( $container, $dir, array $params );
935 * @see FileBackend::getFileList()
936 * @return Traversable|Array|null Returns null on failure
938 final public function getFileList( array $params ) {
939 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
940 if ( $dir === null ) { // invalid storage path
943 if ( $shard !== null ) {
944 // File listing is confined to a single container/shard
945 return $this->getFileListInternal( $fullCont, $dir, $params );
947 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
948 // File listing spans multiple containers/shards
949 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
950 return new FileBackendStoreShardFileIterator( $this,
951 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
956 * Do not call this function from places outside FileBackend
958 * @see FileBackendStore::getFileList()
960 * @param $container string Resolved container name
961 * @param $dir string Resolved path relative to container
962 * @param $params Array
963 * @return Traversable|Array|null Returns null on failure
965 abstract public function getFileListInternal( $container, $dir, array $params );
968 * Return a list of FileOp objects from a list of operations.
969 * Do not call this function from places outside FileBackend.
971 * The result must have the same number of items as the input.
972 * An exception is thrown if an unsupported operation is requested.
974 * @param $ops Array Same format as doOperations()
975 * @return Array List of FileOp objects
976 * @throws MWException
978 final public function getOperationsInternal( array $ops ) {
979 $supportedOps = array(
980 'store' => 'StoreFileOp',
981 'copy' => 'CopyFileOp',
982 'move' => 'MoveFileOp',
983 'delete' => 'DeleteFileOp',
984 'create' => 'CreateFileOp',
985 'null' => 'NullFileOp'
988 $performOps = array(); // array of FileOp objects
989 // Build up ordered array of FileOps...
990 foreach ( $ops as $operation ) {
991 $opName = $operation['op'];
992 if ( isset( $supportedOps[$opName] ) ) {
993 $class = $supportedOps[$opName];
994 // Get params for this operation
995 $params = $operation;
996 // Append the FileOp class
997 $performOps[] = new $class( $this, $params );
999 throw new MWException( "Operation '$opName' is not supported." );
1007 * Get a list of storage paths to lock for a list of operations
1008 * Returns an array with 'sh' (shared) and 'ex' (exclusive) keys,
1009 * each corresponding to a list of storage paths to be locked.
1010 * All returned paths are normalized.
1012 * @param $performOps Array List of FileOp objects
1013 * @return Array ('sh' => list of paths, 'ex' => list of paths)
1015 final public function getPathsToLockForOpsInternal( array $performOps ) {
1016 // Build up a list of files to lock...
1017 $paths = array( 'sh' => array(), 'ex' => array() );
1018 foreach ( $performOps as $fileOp ) {
1019 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1020 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1022 // Optimization: if doing an EX lock anyway, don't also set an SH one
1023 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1024 // Get a shared lock on the parent directory of each path changed
1025 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1031 * @see FileBackend::getScopedLocksForOps()
1034 public function getScopedLocksForOps( array $ops, Status
$status ) {
1035 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1037 $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status ),
1038 $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status )
1043 * @see FileBackend::doOperationsInternal()
1046 final protected function doOperationsInternal( array $ops, array $opts ) {
1047 wfProfileIn( __METHOD__
);
1048 wfProfileIn( __METHOD__
. '-' . $this->name
);
1049 $status = Status
::newGood();
1051 // Build up a list of FileOps...
1052 $performOps = $this->getOperationsInternal( $ops );
1054 // Acquire any locks as needed...
1055 if ( empty( $opts['nonLocking'] ) ) {
1056 // Build up a list of files to lock...
1057 $paths = $this->getPathsToLockForOpsInternal( $performOps );
1058 // Try to lock those files for the scope of this function...
1059 $scopeLockS = $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status );
1060 $scopeLockE = $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status );
1061 if ( !$status->isOK() ) {
1062 wfProfileOut( __METHOD__
. '-' . $this->name
);
1063 wfProfileOut( __METHOD__
);
1064 return $status; // abort
1068 // Clear any file cache entries (after locks acquired)
1069 if ( empty( $opts['preserveCache'] ) ) {
1070 $this->clearCache();
1073 // Load from the persistent file and container caches
1074 $this->primeFileCache( $performOps );
1075 $this->primeContainerCache( $performOps );
1077 // Actually attempt the operation batch...
1078 $opts = $this->setConcurrencyFlags( $opts );
1079 $subStatus = FileOpBatch
::attempt( $performOps, $opts, $this->fileJournal
);
1081 // Merge errors into status fields
1082 $status->merge( $subStatus );
1083 $status->success
= $subStatus->success
; // not done in merge()
1085 wfProfileOut( __METHOD__
. '-' . $this->name
);
1086 wfProfileOut( __METHOD__
);
1091 * @see FileBackend::doQuickOperationsInternal()
1093 * @throws MWException
1095 final protected function doQuickOperationsInternal( array $ops ) {
1096 wfProfileIn( __METHOD__
);
1097 wfProfileIn( __METHOD__
. '-' . $this->name
);
1098 $status = Status
::newGood();
1100 $supportedOps = array( 'create', 'store', 'copy', 'move', 'delete', 'null' );
1101 $async = ( $this->parallelize
=== 'implicit' );
1102 $maxConcurrency = $this->concurrency
; // throttle
1104 $statuses = array(); // array of (index => Status)
1105 $fileOpHandles = array(); // list of (index => handle) arrays
1106 $curFileOpHandles = array(); // current handle batch
1107 // Perform the sync-only ops and build up op handles for the async ops...
1108 foreach ( $ops as $index => $params ) {
1109 if ( !in_array( $params['op'], $supportedOps ) ) {
1110 wfProfileOut( __METHOD__
. '-' . $this->name
);
1111 wfProfileOut( __METHOD__
);
1112 throw new MWException( "Operation '{$params['op']}' is not supported." );
1114 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1115 $subStatus = $this->$method( array( 'async' => $async ) +
$params );
1116 if ( $subStatus->value
instanceof FileBackendStoreOpHandle
) { // async
1117 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1118 $fileOpHandles[] = $curFileOpHandles; // push this batch
1119 $curFileOpHandles = array();
1121 $curFileOpHandles[$index] = $subStatus->value
; // keep index
1122 } else { // error or completed
1123 $statuses[$index] = $subStatus; // keep index
1126 if ( count( $curFileOpHandles ) ) {
1127 $fileOpHandles[] = $curFileOpHandles; // last batch
1129 // Do all the async ops that can be done concurrently...
1130 foreach ( $fileOpHandles as $fileHandleBatch ) {
1131 $statuses = $statuses +
$this->executeOpHandlesInternal( $fileHandleBatch );
1133 // Marshall and merge all the responses...
1134 foreach ( $statuses as $index => $subStatus ) {
1135 $status->merge( $subStatus );
1136 if ( $subStatus->isOK() ) {
1137 $status->success
[$index] = true;
1138 ++
$status->successCount
;
1140 $status->success
[$index] = false;
1141 ++
$status->failCount
;
1145 wfProfileOut( __METHOD__
. '-' . $this->name
);
1146 wfProfileOut( __METHOD__
);
1151 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1152 * The resulting Status object fields will correspond
1153 * to the order in which the handles where given.
1155 * @param $handles Array List of FileBackendStoreOpHandle objects
1156 * @return Array Map of Status objects
1157 * @throws MWException
1159 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1160 wfProfileIn( __METHOD__
);
1161 wfProfileIn( __METHOD__
. '-' . $this->name
);
1162 foreach ( $fileOpHandles as $fileOpHandle ) {
1163 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle
) ) {
1164 throw new MWException( "Given a non-FileBackendStoreOpHandle object." );
1165 } elseif ( $fileOpHandle->backend
->getName() !== $this->getName() ) {
1166 throw new MWException( "Given a FileBackendStoreOpHandle for the wrong backend." );
1169 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1170 foreach ( $fileOpHandles as $fileOpHandle ) {
1171 $fileOpHandle->closeResources();
1173 wfProfileOut( __METHOD__
. '-' . $this->name
);
1174 wfProfileOut( __METHOD__
);
1179 * @see FileBackendStore::executeOpHandlesInternal()
1180 * @param array $fileOpHandles
1181 * @throws MWException
1182 * @return Array List of corresponding Status objects
1184 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1185 foreach ( $fileOpHandles as $fileOpHandle ) { // OK if empty
1186 throw new MWException( "This backend supports no asynchronous operations." );
1192 * @see FileBackend::preloadCache()
1194 final public function preloadCache( array $paths ) {
1195 $fullConts = array(); // full container names
1196 foreach ( $paths as $path ) {
1197 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1198 $fullConts[] = $fullCont;
1200 // Load from the persistent file and container caches
1201 $this->primeContainerCache( $fullConts );
1202 $this->primeFileCache( $paths );
1206 * @see FileBackend::clearCache()
1208 final public function clearCache( array $paths = null ) {
1209 if ( is_array( $paths ) ) {
1210 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1211 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1213 if ( $paths === null ) {
1214 $this->cheapCache
->clear();
1215 $this->expensiveCache
->clear();
1217 foreach ( $paths as $path ) {
1218 $this->cheapCache
->clear( $path );
1219 $this->expensiveCache
->clear( $path );
1222 $this->doClearCache( $paths );
1226 * Clears any additional stat caches for storage paths
1228 * @see FileBackend::clearCache()
1230 * @param $paths Array Storage paths (optional)
1233 protected function doClearCache( array $paths = null ) {}
1236 * Is this a key/value store where directories are just virtual?
1237 * Virtual directories exists in so much as files exists that are
1238 * prefixed with the directory path followed by a forward slash.
1242 abstract protected function directoriesAreVirtual();
1245 * Check if a container name is valid.
1246 * This checks for for length and illegal characters.
1248 * @param $container string
1251 final protected static function isValidContainerName( $container ) {
1252 // This accounts for Swift and S3 restrictions while leaving room
1253 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1254 // This disallows directory separators or traversal characters.
1255 // Note that matching strings URL encode to the same string;
1256 // in Swift, the length restriction is *after* URL encoding.
1257 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1261 * Splits a storage path into an internal container name,
1262 * an internal relative file name, and a container shard suffix.
1263 * Any shard suffix is already appended to the internal container name.
1264 * This also checks that the storage path is valid and within this backend.
1266 * If the container is sharded but a suffix could not be determined,
1267 * this means that the path can only refer to a directory and can only
1268 * be scanned by looking in all the container shards.
1270 * @param $storagePath string
1271 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1273 final protected function resolveStoragePath( $storagePath ) {
1274 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1275 if ( $backend === $this->name
) { // must be for this backend
1276 $relPath = self
::normalizeContainerPath( $relPath );
1277 if ( $relPath !== null ) {
1278 // Get shard for the normalized path if this container is sharded
1279 $cShard = $this->getContainerShard( $container, $relPath );
1280 // Validate and sanitize the relative path (backend-specific)
1281 $relPath = $this->resolveContainerPath( $container, $relPath );
1282 if ( $relPath !== null ) {
1283 // Prepend any wiki ID prefix to the container name
1284 $container = $this->fullContainerName( $container );
1285 if ( self
::isValidContainerName( $container ) ) {
1286 // Validate and sanitize the container name (backend-specific)
1287 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1288 if ( $container !== null ) {
1289 return array( $container, $relPath, $cShard );
1295 return array( null, null, null );
1299 * Like resolveStoragePath() except null values are returned if
1300 * the container is sharded and the shard could not be determined.
1302 * @see FileBackendStore::resolveStoragePath()
1304 * @param $storagePath string
1305 * @return Array (container, path) or (null, null) if invalid
1307 final protected function resolveStoragePathReal( $storagePath ) {
1308 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1309 if ( $cShard !== null ) {
1310 return array( $container, $relPath );
1312 return array( null, null );
1316 * Get the container name shard suffix for a given path.
1317 * Any empty suffix means the container is not sharded.
1319 * @param $container string Container name
1320 * @param $relPath string Storage path relative to the container
1321 * @return string|null Returns null if shard could not be determined
1323 final protected function getContainerShard( $container, $relPath ) {
1324 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1325 if ( $levels == 1 ||
$levels == 2 ) {
1326 // Hash characters are either base 16 or 36
1327 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1328 // Get a regex that represents the shard portion of paths.
1329 // The concatenation of the captures gives us the shard.
1330 if ( $levels === 1 ) { // 16 or 36 shards per container
1331 $hashDirRegex = '(' . $char . ')';
1332 } else { // 256 or 1296 shards per container
1333 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1334 $hashDirRegex = $char . '/(' . $char . '{2})';
1335 } else { // short hash dir format (e.g. "a/b/c")
1336 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1339 // Allow certain directories to be above the hash dirs so as
1340 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1341 // They must be 2+ chars to avoid any hash directory ambiguity.
1343 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1344 return '.' . implode( '', array_slice( $m, 1 ) );
1346 return null; // failed to match
1348 return ''; // no sharding
1352 * Check if a storage path maps to a single shard.
1353 * Container dirs like "a", where the container shards on "x/xy",
1354 * can reside on several shards. Such paths are tricky to handle.
1356 * @param $storagePath string Storage path
1359 final public function isSingleShardPathInternal( $storagePath ) {
1360 list( $c, $r, $shard ) = $this->resolveStoragePath( $storagePath );
1361 return ( $shard !== null );
1365 * Get the sharding config for a container.
1366 * If greater than 0, then all file storage paths within
1367 * the container are required to be hashed accordingly.
1369 * @param $container string
1370 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
1372 final protected function getContainerHashLevels( $container ) {
1373 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1374 $config = $this->shardViaHashLevels
[$container];
1375 $hashLevels = (int)$config['levels'];
1376 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1377 $hashBase = (int)$config['base'];
1378 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1379 return array( $hashLevels, $hashBase, $config['repeat'] );
1383 return array( 0, 0, false ); // no sharding
1387 * Get a list of full container shard suffixes for a container
1389 * @param $container string
1392 final protected function getContainerSuffixes( $container ) {
1394 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1395 if ( $digits > 0 ) {
1396 $numShards = pow( $base, $digits );
1397 for ( $index = 0; $index < $numShards; $index++
) {
1398 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1405 * Get the full container name, including the wiki ID prefix
1407 * @param $container string
1410 final protected function fullContainerName( $container ) {
1411 if ( $this->wikiId
!= '' ) {
1412 return "{$this->wikiId}-$container";
1419 * Resolve a container name, checking if it's allowed by the backend.
1420 * This is intended for internal use, such as encoding illegal chars.
1421 * Subclasses can override this to be more restrictive.
1423 * @param $container string
1424 * @return string|null
1426 protected function resolveContainerName( $container ) {
1431 * Resolve a relative storage path, checking if it's allowed by the backend.
1432 * This is intended for internal use, such as encoding illegal chars or perhaps
1433 * getting absolute paths (e.g. FS based backends). Note that the relative path
1434 * may be the empty string (e.g. the path is simply to the container).
1436 * @param $container string Container name
1437 * @param $relStoragePath string Storage path relative to the container
1438 * @return string|null Path or null if not valid
1440 protected function resolveContainerPath( $container, $relStoragePath ) {
1441 return $relStoragePath;
1445 * Get the cache key for a container
1447 * @param $container string Resolved container name
1450 private function containerCacheKey( $container ) {
1451 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1455 * Set the cached info for a container
1457 * @param $container string Resolved container name
1458 * @param $val mixed Information to cache
1460 final protected function setContainerCache( $container, $val ) {
1461 $this->memCache
->add( $this->containerCacheKey( $container ), $val, 14*86400 );
1465 * Delete the cached info for a container.
1466 * The cache key is salted for a while to prevent race conditions.
1468 * @param $container string Resolved container name
1470 final protected function deleteContainerCache( $container ) {
1471 if ( !$this->memCache
->set( $this->containerCacheKey( $container ), 'PURGED', 300 ) ) {
1472 trigger_error( "Unable to delete stat cache for container $container." );
1477 * Do a batch lookup from cache for container stats for all containers
1478 * used in a list of container names, storage paths, or FileOp objects.
1479 * This loads the persistent cache values into the process cache.
1481 * @param $items Array
1484 final protected function primeContainerCache( array $items ) {
1485 wfProfileIn( __METHOD__
);
1486 wfProfileIn( __METHOD__
. '-' . $this->name
);
1488 $paths = array(); // list of storage paths
1489 $contNames = array(); // (cache key => resolved container name)
1490 // Get all the paths/containers from the items...
1491 foreach ( $items as $item ) {
1492 if ( $item instanceof FileOp
) {
1493 $paths = array_merge( $paths, $item->storagePathsRead() );
1494 $paths = array_merge( $paths, $item->storagePathsChanged() );
1495 } elseif ( self
::isStoragePath( $item ) ) {
1497 } elseif ( is_string( $item ) ) { // full container name
1498 $contNames[$this->containerCacheKey( $item )] = $item;
1501 // Get all the corresponding cache keys for paths...
1502 foreach ( $paths as $path ) {
1503 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1504 if ( $fullCont !== null ) { // valid path for this backend
1505 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1509 $contInfo = array(); // (resolved container name => cache value)
1510 // Get all cache entries for these container cache keys...
1511 $values = $this->memCache
->getMulti( array_keys( $contNames ) );
1512 foreach ( $values as $cacheKey => $val ) {
1513 $contInfo[$contNames[$cacheKey]] = $val;
1516 // Populate the container process cache for the backend...
1517 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1519 wfProfileOut( __METHOD__
. '-' . $this->name
);
1520 wfProfileOut( __METHOD__
);
1524 * Fill the backend-specific process cache given an array of
1525 * resolved container names and their corresponding cached info.
1526 * Only containers that actually exist should appear in the map.
1528 * @param $containerInfo Array Map of resolved container names to cached info
1531 protected function doPrimeContainerCache( array $containerInfo ) {}
1534 * Get the cache key for a file path
1536 * @param $path string Normalized storage path
1539 private function fileCacheKey( $path ) {
1540 return wfMemcKey( 'backend', $this->getName(), 'file', sha1( $path ) );
1544 * Set the cached stat info for a file path.
1545 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1546 * salting for the case when a file is created at a path were there was none before.
1548 * @param $path string Storage path
1549 * @param $val mixed Information to cache
1551 final protected function setFileCache( $path, $val ) {
1552 $path = FileBackend
::normalizeStoragePath( $path );
1553 if ( $path === null ) {
1554 return; // invalid storage path
1556 $this->memCache
->add( $this->fileCacheKey( $path ), $val, 7*86400 );
1560 * Delete the cached stat info for a file path.
1561 * The cache key is salted for a while to prevent race conditions.
1563 * @param $path string Storage path
1565 final protected function deleteFileCache( $path ) {
1566 $path = FileBackend
::normalizeStoragePath( $path );
1567 if ( $path === null ) {
1568 return; // invalid storage path
1570 if ( !$this->memCache
->set( $this->fileCacheKey( $path ), 'PURGED', 300 ) ) {
1571 trigger_error( "Unable to delete stat cache for file $path." );
1576 * Do a batch lookup from cache for file stats for all paths
1577 * used in a list of storage paths or FileOp objects.
1578 * This loads the persistent cache values into the process cache.
1580 * @param $items Array List of storage paths or FileOps
1583 final protected function primeFileCache( array $items ) {
1584 wfProfileIn( __METHOD__
);
1585 wfProfileIn( __METHOD__
. '-' . $this->name
);
1587 $paths = array(); // list of storage paths
1588 $pathNames = array(); // (cache key => storage path)
1589 // Get all the paths/containers from the items...
1590 foreach ( $items as $item ) {
1591 if ( $item instanceof FileOp
) {
1592 $paths = array_merge( $paths, $item->storagePathsRead() );
1593 $paths = array_merge( $paths, $item->storagePathsChanged() );
1594 } elseif ( self
::isStoragePath( $item ) ) {
1595 $paths[] = FileBackend
::normalizeStoragePath( $item );
1598 // Get rid of any paths that failed normalization...
1599 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1600 // Get all the corresponding cache keys for paths...
1601 foreach ( $paths as $path ) {
1602 list( $cont, $rel, $s ) = $this->resolveStoragePath( $path );
1603 if ( $rel !== null ) { // valid path for this backend
1604 $pathNames[$this->fileCacheKey( $path )] = $path;
1607 // Get all cache entries for these container cache keys...
1608 $values = $this->memCache
->getMulti( array_keys( $pathNames ) );
1609 foreach ( $values as $cacheKey => $val ) {
1610 if ( is_array( $val ) ) {
1611 $path = $pathNames[$cacheKey];
1612 $this->cheapCache
->set( $path, 'stat', $val );
1613 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1614 $this->cheapCache
->set( $path, 'sha1',
1615 array( 'hash' => $val['sha1'], 'latest' => $val['latest'] ) );
1620 wfProfileOut( __METHOD__
. '-' . $this->name
);
1621 wfProfileOut( __METHOD__
);
1625 * Set the 'concurrency' option from a list of operation options
1627 * @param $opts array Map of operation options
1630 final protected function setConcurrencyFlags( array $opts ) {
1631 $opts['concurrency'] = 1; // off
1632 if ( $this->parallelize
=== 'implicit' ) {
1633 if ( !isset( $opts['parallelize'] ) ||
$opts['parallelize'] ) {
1634 $opts['concurrency'] = $this->concurrency
;
1636 } elseif ( $this->parallelize
=== 'explicit' ) {
1637 if ( !empty( $opts['parallelize'] ) ) {
1638 $opts['concurrency'] = $this->concurrency
;
1646 * FileBackendStore helper class for performing asynchronous file operations.
1648 * For example, calling FileBackendStore::createInternal() with the "async"
1649 * param flag may result in a Status that contains this object as a value.
1650 * This class is largely backend-specific and is mostly just "magic" to be
1651 * passed to FileBackendStore::executeOpHandlesInternal().
1653 abstract class FileBackendStoreOpHandle
{
1655 public $params = array(); // params to caller functions
1656 /** @var FileBackendStore */
1659 public $resourcesToClose = array();
1661 public $call; // string; name that identifies the function called
1664 * Close all open file handles
1668 public function closeResources() {
1669 array_map( 'fclose', $this->resourcesToClose
);
1674 * FileBackendStore helper function to handle listings that span container shards.
1675 * Do not use this class from places outside of FileBackendStore.
1677 * @ingroup FileBackend
1679 abstract class FileBackendStoreShardListIterator
implements Iterator
{
1680 /** @var FileBackendStore */
1685 protected $shardSuffixes;
1686 protected $container; // string; full container name
1687 protected $directory; // string; resolved relative path
1689 /** @var Traversable */
1691 protected $curShard = 0; // integer
1692 protected $pos = 0; // integer
1695 protected $multiShardPaths = array(); // (rel path => 1)
1698 * @param $backend FileBackendStore
1699 * @param $container string Full storage container name
1700 * @param $dir string Storage directory relative to container
1701 * @param $suffixes Array List of container shard suffixes
1702 * @param $params Array
1704 public function __construct(
1705 FileBackendStore
$backend, $container, $dir, array $suffixes, array $params
1707 $this->backend
= $backend;
1708 $this->container
= $container;
1709 $this->directory
= $dir;
1710 $this->shardSuffixes
= $suffixes;
1711 $this->params
= $params;
1715 * @see Iterator::key()
1718 public function key() {
1723 * @see Iterator::valid()
1726 public function valid() {
1727 if ( $this->iter
instanceof Iterator
) {
1728 return $this->iter
->valid();
1729 } elseif ( is_array( $this->iter
) ) {
1730 return ( current( $this->iter
) !== false ); // no paths can have this value
1732 return false; // some failure?
1736 * @see Iterator::current()
1737 * @return string|bool String or false
1739 public function current() {
1740 return ( $this->iter
instanceof Iterator
)
1741 ?
$this->iter
->current()
1742 : current( $this->iter
);
1746 * @see Iterator::next()
1749 public function next() {
1751 ( $this->iter
instanceof Iterator
) ?
$this->iter
->next() : next( $this->iter
);
1753 $continue = false; // keep scanning shards?
1754 $this->filterViaNext(); // filter out duplicates
1755 // Find the next non-empty shard if no elements are left
1756 if ( !$this->valid() ) {
1757 $this->nextShardIteratorIfNotValid();
1758 $continue = $this->valid(); // re-filter unless we ran out of shards
1760 } while ( $continue );
1764 * @see Iterator::rewind()
1767 public function rewind() {
1769 $this->curShard
= 0;
1770 $this->setIteratorFromCurrentShard();
1772 $continue = false; // keep scanning shards?
1773 $this->filterViaNext(); // filter out duplicates
1774 // Find the next non-empty shard if no elements are left
1775 if ( !$this->valid() ) {
1776 $this->nextShardIteratorIfNotValid();
1777 $continue = $this->valid(); // re-filter unless we ran out of shards
1779 } while ( $continue );
1783 * Filter out duplicate items by advancing to the next ones
1785 protected function filterViaNext() {
1786 while ( $this->valid() ) {
1787 $rel = $this->iter
->current(); // path relative to given directory
1788 $path = $this->params
['dir'] . "/{$rel}"; // full storage path
1789 if ( $this->backend
->isSingleShardPathInternal( $path ) ) {
1790 break; // path is only on one shard; no issue with duplicates
1791 } elseif ( isset( $this->multiShardPaths
[$rel] ) ) {
1792 // Don't keep listing paths that are on multiple shards
1793 ( $this->iter
instanceof Iterator
) ?
$this->iter
->next() : next( $this->iter
);
1795 $this->multiShardPaths
[$rel] = 1;
1802 * If the list iterator for this container shard is out of items,
1803 * then move on to the next container that has items.
1804 * If there are none, then it advances to the last container.
1806 protected function nextShardIteratorIfNotValid() {
1807 while ( !$this->valid() && ++
$this->curShard
< count( $this->shardSuffixes
) ) {
1808 $this->setIteratorFromCurrentShard();
1813 * Set the list iterator to that of the current container shard
1815 protected function setIteratorFromCurrentShard() {
1816 $this->iter
= $this->listFromShard(
1817 $this->container
. $this->shardSuffixes
[$this->curShard
],
1818 $this->directory
, $this->params
);
1819 // Start loading results so that current() works
1820 if ( $this->iter
) {
1821 ( $this->iter
instanceof Iterator
) ?
$this->iter
->rewind() : reset( $this->iter
);
1826 * Get the list for a given container shard
1828 * @param $container string Resolved container name
1829 * @param $dir string Resolved path relative to container
1830 * @param $params Array
1831 * @return Traversable|Array|null
1833 abstract protected function listFromShard( $container, $dir, array $params );
1837 * Iterator for listing directories
1839 class FileBackendStoreShardDirIterator
extends FileBackendStoreShardListIterator
{
1841 * @see FileBackendStoreShardListIterator::listFromShard()
1842 * @return Array|null|Traversable
1844 protected function listFromShard( $container, $dir, array $params ) {
1845 return $this->backend
->getDirectoryListInternal( $container, $dir, $params );
1850 * Iterator for listing regular files
1852 class FileBackendStoreShardFileIterator
extends FileBackendStoreShardListIterator
{
1854 * @see FileBackendStoreShardListIterator::listFromShard()
1855 * @return Array|null|Traversable
1857 protected function listFromShard( $container, $dir, array $params ) {
1858 return $this->backend
->getFileListInternal( $container, $dir, $params );