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 * Do not call this function from places outside FileBackend and FileOp.
89 * - content : the raw file contents
90 * - dst : destination storage path
91 * - overwrite : overwrite any file that exists at the destination
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 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
110 $this->deleteFileCache( $params['dst'] ); // persistent cache
113 wfProfileOut( __METHOD__
. '-' . $this->name
);
114 wfProfileOut( __METHOD__
);
119 * @see FileBackendStore::createInternal()
121 abstract protected function doCreateInternal( array $params );
124 * Store a file into the backend from a file on disk.
125 * Do not call this function from places outside FileBackend and FileOp.
128 * - src : source path on disk
129 * - dst : destination storage path
130 * - overwrite : overwrite any file that exists at the destination
131 * - disposition : Content-Disposition header value for the destination
132 * - async : Status will be returned immediately if supported.
133 * If the status is OK, then its value field will be
134 * set to a FileBackendStoreOpHandle object.
136 * @param $params Array
139 final public function storeInternal( array $params ) {
140 wfProfileIn( __METHOD__
);
141 wfProfileIn( __METHOD__
. '-' . $this->name
);
142 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
143 $status = Status
::newFatal( 'backend-fail-maxsize',
144 $params['dst'], $this->maxFileSizeInternal() );
146 $status = $this->doStoreInternal( $params );
147 $this->clearCache( array( $params['dst'] ) );
148 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
149 $this->deleteFileCache( $params['dst'] ); // persistent cache
152 wfProfileOut( __METHOD__
. '-' . $this->name
);
153 wfProfileOut( __METHOD__
);
158 * @see FileBackendStore::storeInternal()
160 abstract protected function doStoreInternal( array $params );
163 * Copy a file from one storage path to another in the backend.
164 * Do not call this function from places outside FileBackend and FileOp.
167 * - src : source storage path
168 * - dst : destination storage path
169 * - overwrite : overwrite any file that exists at the destination
170 * - disposition : Content-Disposition header value for the destination
171 * - async : Status will be returned immediately if supported.
172 * If the status is OK, then its value field will be
173 * set to a FileBackendStoreOpHandle object.
175 * @param $params Array
178 final public function copyInternal( array $params ) {
179 wfProfileIn( __METHOD__
);
180 wfProfileIn( __METHOD__
. '-' . $this->name
);
181 $status = $this->doCopyInternal( $params );
182 $this->clearCache( array( $params['dst'] ) );
183 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
184 $this->deleteFileCache( $params['dst'] ); // persistent cache
186 wfProfileOut( __METHOD__
. '-' . $this->name
);
187 wfProfileOut( __METHOD__
);
192 * @see FileBackendStore::copyInternal()
194 abstract protected function doCopyInternal( array $params );
197 * Delete a file at the storage path.
198 * Do not call this function from places outside FileBackend and FileOp.
201 * - src : source storage path
202 * - ignoreMissingSource : do nothing if the source file does not exist
203 * - async : Status will be returned immediately if supported.
204 * If the status is OK, then its value field will be
205 * set to a FileBackendStoreOpHandle object.
207 * @param $params Array
210 final public function deleteInternal( array $params ) {
211 wfProfileIn( __METHOD__
);
212 wfProfileIn( __METHOD__
. '-' . $this->name
);
213 $status = $this->doDeleteInternal( $params );
214 $this->clearCache( array( $params['src'] ) );
215 $this->deleteFileCache( $params['src'] ); // persistent cache
216 wfProfileOut( __METHOD__
. '-' . $this->name
);
217 wfProfileOut( __METHOD__
);
222 * @see FileBackendStore::deleteInternal()
224 abstract protected function doDeleteInternal( array $params );
227 * Move a file from one storage path to another in the backend.
228 * Do not call this function from places outside FileBackend and FileOp.
231 * - src : source storage path
232 * - dst : destination storage path
233 * - overwrite : overwrite any file that exists at the destination
234 * - disposition : Content-Disposition header value for the destination
235 * - async : Status will be returned immediately if supported.
236 * If the status is OK, then its value field will be
237 * set to a FileBackendStoreOpHandle object.
239 * @param $params Array
242 final public function moveInternal( array $params ) {
243 wfProfileIn( __METHOD__
);
244 wfProfileIn( __METHOD__
. '-' . $this->name
);
245 $status = $this->doMoveInternal( $params );
246 $this->clearCache( array( $params['src'], $params['dst'] ) );
247 $this->deleteFileCache( $params['src'] ); // persistent cache
248 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
249 $this->deleteFileCache( $params['dst'] ); // persistent cache
251 wfProfileOut( __METHOD__
. '-' . $this->name
);
252 wfProfileOut( __METHOD__
);
257 * @see FileBackendStore::moveInternal()
260 protected function doMoveInternal( array $params ) {
261 unset( $params['async'] ); // two steps, won't work here :)
262 // Copy source to dest
263 $status = $this->copyInternal( $params );
264 if ( $status->isOK() ) {
265 // Delete source (only fails due to races or medium going down)
266 $status->merge( $this->deleteInternal( array( 'src' => $params['src'] ) ) );
267 $status->setResult( true, $status->value
); // ignore delete() errors
273 * No-op file operation that does nothing.
274 * Do not call this function from places outside FileBackend and FileOp.
276 * @param $params Array
279 final public function nullInternal( array $params ) {
280 return Status
::newGood();
284 * @see FileBackend::concatenate()
287 final public function concatenate( array $params ) {
288 wfProfileIn( __METHOD__
);
289 wfProfileIn( __METHOD__
. '-' . $this->name
);
290 $status = Status
::newGood();
292 // Try to lock the source files for the scope of this function
293 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager
::LOCK_UW
, $status );
294 if ( $status->isOK() ) {
295 // Actually do the file concatenation...
296 $start_time = microtime( true );
297 $status->merge( $this->doConcatenate( $params ) );
298 $sec = microtime( true ) - $start_time;
299 if ( !$status->isOK() ) {
300 wfDebugLog( 'FileOperation', get_class( $this ) . " failed to concatenate " .
301 count( $params['srcs'] ) . " file(s) [$sec sec]" );
305 wfProfileOut( __METHOD__
. '-' . $this->name
);
306 wfProfileOut( __METHOD__
);
311 * @see FileBackendStore::concatenate()
314 protected function doConcatenate( array $params ) {
315 $status = Status
::newGood();
316 $tmpPath = $params['dst']; // convenience
317 unset( $params['latest'] ); // sanity
319 // Check that the specified temp file is valid...
320 wfSuppressWarnings();
321 $ok = ( is_file( $tmpPath ) && filesize( $tmpPath ) == 0 );
323 if ( !$ok ) { // not present or not empty
324 $status->fatal( 'backend-fail-opentemp', $tmpPath );
328 // Get local FS versions of the chunks needed for the concatenation...
329 $fsFiles = $this->getLocalReferenceMulti( $params );
330 foreach ( $fsFiles as $path => &$fsFile ) {
331 if ( !$fsFile ) { // chunk failed to download?
332 $fsFile = $this->getLocalReference( array( 'src' => $path ) );
333 if ( !$fsFile ) { // retry failed?
334 $status->fatal( 'backend-fail-read', $path );
339 unset( $fsFile ); // unset reference so we can reuse $fsFile
341 // Get a handle for the destination temp file
342 $tmpHandle = fopen( $tmpPath, 'ab' );
343 if ( $tmpHandle === false ) {
344 $status->fatal( 'backend-fail-opentemp', $tmpPath );
348 // Build up the temp file using the source chunks (in order)...
349 foreach ( $fsFiles as $virtualSource => $fsFile ) {
350 // Get a handle to the local FS version
351 $sourceHandle = fopen( $fsFile->getPath(), 'rb' );
352 if ( $sourceHandle === false ) {
353 fclose( $tmpHandle );
354 $status->fatal( 'backend-fail-read', $virtualSource );
357 // Append chunk to file (pass chunk size to avoid magic quotes)
358 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
359 fclose( $sourceHandle );
360 fclose( $tmpHandle );
361 $status->fatal( 'backend-fail-writetemp', $tmpPath );
364 fclose( $sourceHandle );
366 if ( !fclose( $tmpHandle ) ) {
367 $status->fatal( 'backend-fail-closetemp', $tmpPath );
371 clearstatcache(); // temp file changed
377 * @see FileBackend::doPrepare()
380 final protected function doPrepare( array $params ) {
381 wfProfileIn( __METHOD__
);
382 wfProfileIn( __METHOD__
. '-' . $this->name
);
384 $status = Status
::newGood();
385 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
386 if ( $dir === null ) {
387 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
388 wfProfileOut( __METHOD__
. '-' . $this->name
);
389 wfProfileOut( __METHOD__
);
390 return $status; // invalid storage path
393 if ( $shard !== null ) { // confined to a single container/shard
394 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
395 } else { // directory is on several shards
396 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
397 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
398 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
399 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
403 wfProfileOut( __METHOD__
. '-' . $this->name
);
404 wfProfileOut( __METHOD__
);
409 * @see FileBackendStore::doPrepare()
412 protected function doPrepareInternal( $container, $dir, array $params ) {
413 return Status
::newGood();
417 * @see FileBackend::doSecure()
420 final protected function doSecure( array $params ) {
421 wfProfileIn( __METHOD__
);
422 wfProfileIn( __METHOD__
. '-' . $this->name
);
423 $status = Status
::newGood();
425 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
426 if ( $dir === null ) {
427 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
428 wfProfileOut( __METHOD__
. '-' . $this->name
);
429 wfProfileOut( __METHOD__
);
430 return $status; // invalid storage path
433 if ( $shard !== null ) { // confined to a single container/shard
434 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
435 } else { // directory is on several shards
436 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
437 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
438 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
439 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
443 wfProfileOut( __METHOD__
. '-' . $this->name
);
444 wfProfileOut( __METHOD__
);
449 * @see FileBackendStore::doSecure()
452 protected function doSecureInternal( $container, $dir, array $params ) {
453 return Status
::newGood();
457 * @see FileBackend::doPublish()
460 final protected function doPublish( array $params ) {
461 wfProfileIn( __METHOD__
);
462 wfProfileIn( __METHOD__
. '-' . $this->name
);
463 $status = Status
::newGood();
465 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
466 if ( $dir === null ) {
467 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
468 wfProfileOut( __METHOD__
. '-' . $this->name
);
469 wfProfileOut( __METHOD__
);
470 return $status; // invalid storage path
473 if ( $shard !== null ) { // confined to a single container/shard
474 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
475 } else { // directory is on several shards
476 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
477 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
478 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
479 $status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
483 wfProfileOut( __METHOD__
. '-' . $this->name
);
484 wfProfileOut( __METHOD__
);
489 * @see FileBackendStore::doPublish()
492 protected function doPublishInternal( $container, $dir, array $params ) {
493 return Status
::newGood();
497 * @see FileBackend::doClean()
500 final protected function doClean( array $params ) {
501 wfProfileIn( __METHOD__
);
502 wfProfileIn( __METHOD__
. '-' . $this->name
);
503 $status = Status
::newGood();
505 // Recursive: first delete all empty subdirs recursively
506 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
507 $subDirsRel = $this->getTopDirectoryList( array( 'dir' => $params['dir'] ) );
508 if ( $subDirsRel !== null ) { // no errors
509 foreach ( $subDirsRel as $subDirRel ) {
510 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
511 $status->merge( $this->doClean( array( 'dir' => $subDir ) +
$params ) );
516 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
517 if ( $dir === null ) {
518 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
519 wfProfileOut( __METHOD__
. '-' . $this->name
);
520 wfProfileOut( __METHOD__
);
521 return $status; // invalid storage path
524 // Attempt to lock this directory...
525 $filesLockEx = array( $params['dir'] );
526 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
527 if ( !$status->isOK() ) {
528 wfProfileOut( __METHOD__
. '-' . $this->name
);
529 wfProfileOut( __METHOD__
);
530 return $status; // abort
533 if ( $shard !== null ) { // confined to a single container/shard
534 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
535 $this->deleteContainerCache( $fullCont ); // purge cache
536 } else { // directory is on several shards
537 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
538 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
539 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
540 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
541 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
545 wfProfileOut( __METHOD__
. '-' . $this->name
);
546 wfProfileOut( __METHOD__
);
551 * @see FileBackendStore::doClean()
554 protected function doCleanInternal( $container, $dir, array $params ) {
555 return Status
::newGood();
559 * @see FileBackend::fileExists()
562 final public function fileExists( array $params ) {
563 wfProfileIn( __METHOD__
);
564 wfProfileIn( __METHOD__
. '-' . $this->name
);
565 $stat = $this->getFileStat( $params );
566 wfProfileOut( __METHOD__
. '-' . $this->name
);
567 wfProfileOut( __METHOD__
);
568 return ( $stat === null ) ?
null : (bool)$stat; // null => failure
572 * @see FileBackend::getFileTimestamp()
575 final public function getFileTimestamp( array $params ) {
576 wfProfileIn( __METHOD__
);
577 wfProfileIn( __METHOD__
. '-' . $this->name
);
578 $stat = $this->getFileStat( $params );
579 wfProfileOut( __METHOD__
. '-' . $this->name
);
580 wfProfileOut( __METHOD__
);
581 return $stat ?
$stat['mtime'] : false;
585 * @see FileBackend::getFileSize()
588 final public function getFileSize( array $params ) {
589 wfProfileIn( __METHOD__
);
590 wfProfileIn( __METHOD__
. '-' . $this->name
);
591 $stat = $this->getFileStat( $params );
592 wfProfileOut( __METHOD__
. '-' . $this->name
);
593 wfProfileOut( __METHOD__
);
594 return $stat ?
$stat['size'] : false;
598 * @see FileBackend::getFileStat()
601 final public function getFileStat( array $params ) {
602 $path = self
::normalizeStoragePath( $params['src'] );
603 if ( $path === null ) {
604 return false; // invalid storage path
606 wfProfileIn( __METHOD__
);
607 wfProfileIn( __METHOD__
. '-' . $this->name
);
608 $latest = !empty( $params['latest'] ); // use latest data?
609 if ( !$this->cheapCache
->has( $path, 'stat' ) ) {
610 $this->primeFileCache( array( $path ) ); // check persistent cache
612 if ( $this->cheapCache
->has( $path, 'stat' ) ) {
613 $stat = $this->cheapCache
->get( $path, 'stat' );
614 // If we want the latest data, check that this cached
615 // value was in fact fetched with the latest available data.
616 if ( !$latest ||
$stat['latest'] ) {
617 wfProfileOut( __METHOD__
. '-' . $this->name
);
618 wfProfileOut( __METHOD__
);
622 wfProfileIn( __METHOD__
. '-miss' );
623 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
624 $stat = $this->doGetFileStat( $params );
625 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
626 wfProfileOut( __METHOD__
. '-miss' );
627 if ( is_array( $stat ) ) { // don't cache negatives
628 $stat['latest'] = $latest;
629 $this->cheapCache
->set( $path, 'stat', $stat );
630 $this->setFileCache( $path, $stat ); // update persistent cache
631 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
632 $this->cheapCache
->set( $path, 'sha1',
633 array( 'hash' => $stat['sha1'], 'latest' => $latest ) );
636 wfDebug( __METHOD__
. ": File $path does not exist.\n" );
638 wfProfileOut( __METHOD__
. '-' . $this->name
);
639 wfProfileOut( __METHOD__
);
644 * @see FileBackendStore::getFileStat()
646 abstract protected function doGetFileStat( array $params );
649 * @see FileBackend::getFileContentsMulti()
652 public function getFileContentsMulti( array $params ) {
653 wfProfileIn( __METHOD__
);
654 wfProfileIn( __METHOD__
. '-' . $this->name
);
656 $params = $this->setConcurrencyFlags( $params );
657 $contents = $this->doGetFileContentsMulti( $params );
659 wfProfileOut( __METHOD__
. '-' . $this->name
);
660 wfProfileOut( __METHOD__
);
665 * @see FileBackendStore::getFileContentsMulti()
668 protected function doGetFileContentsMulti( array $params ) {
670 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
671 wfSuppressWarnings();
672 $contents[$path] = $fsFile ?
file_get_contents( $fsFile->getPath() ) : false;
679 * @see FileBackend::getFileSha1Base36()
680 * @return bool|string
682 final public function getFileSha1Base36( array $params ) {
683 $path = self
::normalizeStoragePath( $params['src'] );
684 if ( $path === null ) {
685 return false; // invalid storage path
687 wfProfileIn( __METHOD__
);
688 wfProfileIn( __METHOD__
. '-' . $this->name
);
689 $latest = !empty( $params['latest'] ); // use latest data?
690 if ( $this->cheapCache
->has( $path, 'sha1' ) ) {
691 $stat = $this->cheapCache
->get( $path, 'sha1' );
692 // If we want the latest data, check that this cached
693 // value was in fact fetched with the latest available data.
694 if ( !$latest ||
$stat['latest'] ) {
695 wfProfileOut( __METHOD__
. '-' . $this->name
);
696 wfProfileOut( __METHOD__
);
697 return $stat['hash'];
700 wfProfileIn( __METHOD__
. '-miss' );
701 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
702 $hash = $this->doGetFileSha1Base36( $params );
703 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
704 wfProfileOut( __METHOD__
. '-miss' );
705 if ( $hash ) { // don't cache negatives
706 $this->cheapCache
->set( $path, 'sha1',
707 array( 'hash' => $hash, 'latest' => $latest ) );
709 wfProfileOut( __METHOD__
. '-' . $this->name
);
710 wfProfileOut( __METHOD__
);
715 * @see FileBackendStore::getFileSha1Base36()
716 * @return bool|string
718 protected function doGetFileSha1Base36( array $params ) {
719 $fsFile = $this->getLocalReference( $params );
723 return $fsFile->getSha1Base36();
728 * @see FileBackend::getFileProps()
731 final public function getFileProps( array $params ) {
732 wfProfileIn( __METHOD__
);
733 wfProfileIn( __METHOD__
. '-' . $this->name
);
734 $fsFile = $this->getLocalReference( $params );
735 $props = $fsFile ?
$fsFile->getProps() : FSFile
::placeholderProps();
736 wfProfileOut( __METHOD__
. '-' . $this->name
);
737 wfProfileOut( __METHOD__
);
742 * @see FileBackend::getLocalReferenceMulti()
745 final public function getLocalReferenceMulti( array $params ) {
746 wfProfileIn( __METHOD__
);
747 wfProfileIn( __METHOD__
. '-' . $this->name
);
749 $params = $this->setConcurrencyFlags( $params );
751 $fsFiles = array(); // (path => FSFile)
752 $latest = !empty( $params['latest'] ); // use latest data?
753 // Reuse any files already in process cache...
754 foreach ( $params['srcs'] as $src ) {
755 $path = self
::normalizeStoragePath( $src );
756 if ( $path === null ) {
757 $fsFiles[$src] = null; // invalid storage path
758 } elseif ( $this->expensiveCache
->has( $path, 'localRef' ) ) {
759 $val = $this->expensiveCache
->get( $path, 'localRef' );
760 // If we want the latest data, check that this cached
761 // value was in fact fetched with the latest available data.
762 if ( !$latest ||
$val['latest'] ) {
763 $fsFiles[$src] = $val['object'];
767 // Fetch local references of any remaning files...
768 $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
769 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
770 $fsFiles[$path] = $fsFile;
771 if ( $fsFile ) { // update the process cache...
772 $this->expensiveCache
->set( $path, 'localRef',
773 array( 'object' => $fsFile, 'latest' => $latest ) );
777 wfProfileOut( __METHOD__
. '-' . $this->name
);
778 wfProfileOut( __METHOD__
);
783 * @see FileBackendStore::getLocalReferenceMulti()
786 protected function doGetLocalReferenceMulti( array $params ) {
787 return $this->doGetLocalCopyMulti( $params );
791 * @see FileBackend::getLocalCopyMulti()
794 final public function getLocalCopyMulti( array $params ) {
795 wfProfileIn( __METHOD__
);
796 wfProfileIn( __METHOD__
. '-' . $this->name
);
798 $params = $this->setConcurrencyFlags( $params );
799 $tmpFiles = $this->doGetLocalCopyMulti( $params );
801 wfProfileOut( __METHOD__
. '-' . $this->name
);
802 wfProfileOut( __METHOD__
);
807 * @see FileBackendStore::getLocalCopyMulti()
810 abstract protected function doGetLocalCopyMulti( array $params );
813 * @see FileBackend::streamFile()
816 final public function streamFile( array $params ) {
817 wfProfileIn( __METHOD__
);
818 wfProfileIn( __METHOD__
. '-' . $this->name
);
819 $status = Status
::newGood();
821 $info = $this->getFileStat( $params );
822 if ( !$info ) { // let StreamFile handle the 404
823 $status->fatal( 'backend-fail-notexists', $params['src'] );
826 // Set output buffer and HTTP headers for stream
827 $extraHeaders = isset( $params['headers'] ) ?
$params['headers'] : array();
828 $res = StreamFile
::prepareForStream( $params['src'], $info, $extraHeaders );
829 if ( $res == StreamFile
::NOT_MODIFIED
) {
830 // do nothing; client cache is up to date
831 } elseif ( $res == StreamFile
::READY_STREAM
) {
832 wfProfileIn( __METHOD__
. '-send' );
833 wfProfileIn( __METHOD__
. '-send-' . $this->name
);
834 $status = $this->doStreamFile( $params );
835 wfProfileOut( __METHOD__
. '-send-' . $this->name
);
836 wfProfileOut( __METHOD__
. '-send' );
837 if ( !$status->isOK() ) {
838 // Per bug 41113, nasty things can happen if bad cache entries get
839 // stuck in cache. It's also possible that this error can come up
840 // with simple race conditions. Clear out the stat cache to be safe.
841 $this->clearCache( array( $params['src'] ) );
842 $this->deleteFileCache( $params['src'] );
843 trigger_error( "Bad stat cache or race condition for file {$params['src']}." );
846 $status->fatal( 'backend-fail-stream', $params['src'] );
849 wfProfileOut( __METHOD__
. '-' . $this->name
);
850 wfProfileOut( __METHOD__
);
855 * @see FileBackendStore::streamFile()
858 protected function doStreamFile( array $params ) {
859 $status = Status
::newGood();
861 $fsFile = $this->getLocalReference( $params );
863 $status->fatal( 'backend-fail-stream', $params['src'] );
864 } elseif ( !readfile( $fsFile->getPath() ) ) {
865 $status->fatal( 'backend-fail-stream', $params['src'] );
872 * @see FileBackend::directoryExists()
875 final public function directoryExists( array $params ) {
876 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
877 if ( $dir === null ) {
878 return false; // invalid storage path
880 if ( $shard !== null ) { // confined to a single container/shard
881 return $this->doDirectoryExists( $fullCont, $dir, $params );
882 } else { // directory is on several shards
883 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
884 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
885 $res = false; // response
886 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
887 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
891 } elseif ( $exists === null ) { // error?
892 $res = null; // if we don't find anything, it is indeterminate
900 * @see FileBackendStore::directoryExists()
902 * @param $container string Resolved container name
903 * @param $dir string Resolved path relative to container
904 * @param $params Array
907 abstract protected function doDirectoryExists( $container, $dir, array $params );
910 * @see FileBackend::getDirectoryList()
911 * @return Traversable|Array|null Returns null on failure
913 final public function getDirectoryList( array $params ) {
914 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
915 if ( $dir === null ) { // invalid storage path
918 if ( $shard !== null ) {
919 // File listing is confined to a single container/shard
920 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
922 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
923 // File listing spans multiple containers/shards
924 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
925 return new FileBackendStoreShardDirIterator( $this,
926 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
931 * Do not call this function from places outside FileBackend
933 * @see FileBackendStore::getDirectoryList()
935 * @param $container string Resolved container name
936 * @param $dir string Resolved path relative to container
937 * @param $params Array
938 * @return Traversable|Array|null Returns null on failure
940 abstract public function getDirectoryListInternal( $container, $dir, array $params );
943 * @see FileBackend::getFileList()
944 * @return Traversable|Array|null Returns null on failure
946 final public function getFileList( array $params ) {
947 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
948 if ( $dir === null ) { // invalid storage path
951 if ( $shard !== null ) {
952 // File listing is confined to a single container/shard
953 return $this->getFileListInternal( $fullCont, $dir, $params );
955 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
956 // File listing spans multiple containers/shards
957 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
958 return new FileBackendStoreShardFileIterator( $this,
959 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
964 * Do not call this function from places outside FileBackend
966 * @see FileBackendStore::getFileList()
968 * @param $container string Resolved container name
969 * @param $dir string Resolved path relative to container
970 * @param $params Array
971 * @return Traversable|Array|null Returns null on failure
973 abstract public function getFileListInternal( $container, $dir, array $params );
976 * Return a list of FileOp objects from a list of operations.
977 * Do not call this function from places outside FileBackend.
979 * The result must have the same number of items as the input.
980 * An exception is thrown if an unsupported operation is requested.
982 * @param $ops Array Same format as doOperations()
983 * @return Array List of FileOp objects
984 * @throws MWException
986 final public function getOperationsInternal( array $ops ) {
987 $supportedOps = array(
988 'store' => 'StoreFileOp',
989 'copy' => 'CopyFileOp',
990 'move' => 'MoveFileOp',
991 'delete' => 'DeleteFileOp',
992 'create' => 'CreateFileOp',
993 'null' => 'NullFileOp'
996 $performOps = array(); // array of FileOp objects
997 // Build up ordered array of FileOps...
998 foreach ( $ops as $operation ) {
999 $opName = $operation['op'];
1000 if ( isset( $supportedOps[$opName] ) ) {
1001 $class = $supportedOps[$opName];
1002 // Get params for this operation
1003 $params = $operation;
1004 // Append the FileOp class
1005 $performOps[] = new $class( $this, $params );
1007 throw new MWException( "Operation '$opName' is not supported." );
1015 * Get a list of storage paths to lock for a list of operations
1016 * Returns an array with 'sh' (shared) and 'ex' (exclusive) keys,
1017 * each corresponding to a list of storage paths to be locked.
1018 * All returned paths are normalized.
1020 * @param $performOps Array List of FileOp objects
1021 * @return Array ('sh' => list of paths, 'ex' => list of paths)
1023 final public function getPathsToLockForOpsInternal( array $performOps ) {
1024 // Build up a list of files to lock...
1025 $paths = array( 'sh' => array(), 'ex' => array() );
1026 foreach ( $performOps as $fileOp ) {
1027 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1028 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1030 // Optimization: if doing an EX lock anyway, don't also set an SH one
1031 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1032 // Get a shared lock on the parent directory of each path changed
1033 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1039 * @see FileBackend::getScopedLocksForOps()
1042 public function getScopedLocksForOps( array $ops, Status
$status ) {
1043 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1045 $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status ),
1046 $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status )
1051 * @see FileBackend::doOperationsInternal()
1054 final protected function doOperationsInternal( array $ops, array $opts ) {
1055 wfProfileIn( __METHOD__
);
1056 wfProfileIn( __METHOD__
. '-' . $this->name
);
1057 $status = Status
::newGood();
1059 // Build up a list of FileOps...
1060 $performOps = $this->getOperationsInternal( $ops );
1062 // Acquire any locks as needed...
1063 if ( empty( $opts['nonLocking'] ) ) {
1064 // Build up a list of files to lock...
1065 $paths = $this->getPathsToLockForOpsInternal( $performOps );
1066 // Try to lock those files for the scope of this function...
1067 $scopeLockS = $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status );
1068 $scopeLockE = $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status );
1069 if ( !$status->isOK() ) {
1070 wfProfileOut( __METHOD__
. '-' . $this->name
);
1071 wfProfileOut( __METHOD__
);
1072 return $status; // abort
1076 // Clear any file cache entries (after locks acquired)
1077 if ( empty( $opts['preserveCache'] ) ) {
1078 $this->clearCache();
1081 // Load from the persistent file and container caches
1082 $this->primeFileCache( $performOps );
1083 $this->primeContainerCache( $performOps );
1085 // Actually attempt the operation batch...
1086 $opts = $this->setConcurrencyFlags( $opts );
1087 $subStatus = FileOpBatch
::attempt( $performOps, $opts, $this->fileJournal
);
1089 // Merge errors into status fields
1090 $status->merge( $subStatus );
1091 $status->success
= $subStatus->success
; // not done in merge()
1093 wfProfileOut( __METHOD__
. '-' . $this->name
);
1094 wfProfileOut( __METHOD__
);
1099 * @see FileBackend::doQuickOperationsInternal()
1101 * @throws MWException
1103 final protected function doQuickOperationsInternal( array $ops ) {
1104 wfProfileIn( __METHOD__
);
1105 wfProfileIn( __METHOD__
. '-' . $this->name
);
1106 $status = Status
::newGood();
1108 $supportedOps = array( 'create', 'store', 'copy', 'move', 'delete', 'null' );
1109 $async = ( $this->parallelize
=== 'implicit' );
1110 $maxConcurrency = $this->concurrency
; // throttle
1112 $statuses = array(); // array of (index => Status)
1113 $fileOpHandles = array(); // list of (index => handle) arrays
1114 $curFileOpHandles = array(); // current handle batch
1115 // Perform the sync-only ops and build up op handles for the async ops...
1116 foreach ( $ops as $index => $params ) {
1117 if ( !in_array( $params['op'], $supportedOps ) ) {
1118 wfProfileOut( __METHOD__
. '-' . $this->name
);
1119 wfProfileOut( __METHOD__
);
1120 throw new MWException( "Operation '{$params['op']}' is not supported." );
1122 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1123 $subStatus = $this->$method( array( 'async' => $async ) +
$params );
1124 if ( $subStatus->value
instanceof FileBackendStoreOpHandle
) { // async
1125 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1126 $fileOpHandles[] = $curFileOpHandles; // push this batch
1127 $curFileOpHandles = array();
1129 $curFileOpHandles[$index] = $subStatus->value
; // keep index
1130 } else { // error or completed
1131 $statuses[$index] = $subStatus; // keep index
1134 if ( count( $curFileOpHandles ) ) {
1135 $fileOpHandles[] = $curFileOpHandles; // last batch
1137 // Do all the async ops that can be done concurrently...
1138 foreach ( $fileOpHandles as $fileHandleBatch ) {
1139 $statuses = $statuses +
$this->executeOpHandlesInternal( $fileHandleBatch );
1141 // Marshall and merge all the responses...
1142 foreach ( $statuses as $index => $subStatus ) {
1143 $status->merge( $subStatus );
1144 if ( $subStatus->isOK() ) {
1145 $status->success
[$index] = true;
1146 ++
$status->successCount
;
1148 $status->success
[$index] = false;
1149 ++
$status->failCount
;
1153 wfProfileOut( __METHOD__
. '-' . $this->name
);
1154 wfProfileOut( __METHOD__
);
1159 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1160 * The resulting Status object fields will correspond
1161 * to the order in which the handles where given.
1163 * @param $handles Array List of FileBackendStoreOpHandle objects
1164 * @return Array Map of Status objects
1165 * @throws MWException
1167 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1168 wfProfileIn( __METHOD__
);
1169 wfProfileIn( __METHOD__
. '-' . $this->name
);
1170 foreach ( $fileOpHandles as $fileOpHandle ) {
1171 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle
) ) {
1172 throw new MWException( "Given a non-FileBackendStoreOpHandle object." );
1173 } elseif ( $fileOpHandle->backend
->getName() !== $this->getName() ) {
1174 throw new MWException( "Given a FileBackendStoreOpHandle for the wrong backend." );
1177 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1178 foreach ( $fileOpHandles as $fileOpHandle ) {
1179 $fileOpHandle->closeResources();
1181 wfProfileOut( __METHOD__
. '-' . $this->name
);
1182 wfProfileOut( __METHOD__
);
1187 * @see FileBackendStore::executeOpHandlesInternal()
1188 * @param array $fileOpHandles
1189 * @throws MWException
1190 * @return Array List of corresponding Status objects
1192 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1193 foreach ( $fileOpHandles as $fileOpHandle ) { // OK if empty
1194 throw new MWException( "This backend supports no asynchronous operations." );
1200 * @see FileBackend::preloadCache()
1202 final public function preloadCache( array $paths ) {
1203 $fullConts = array(); // full container names
1204 foreach ( $paths as $path ) {
1205 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1206 $fullConts[] = $fullCont;
1208 // Load from the persistent file and container caches
1209 $this->primeContainerCache( $fullConts );
1210 $this->primeFileCache( $paths );
1214 * @see FileBackend::clearCache()
1216 final public function clearCache( array $paths = null ) {
1217 if ( is_array( $paths ) ) {
1218 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1219 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1221 if ( $paths === null ) {
1222 $this->cheapCache
->clear();
1223 $this->expensiveCache
->clear();
1225 foreach ( $paths as $path ) {
1226 $this->cheapCache
->clear( $path );
1227 $this->expensiveCache
->clear( $path );
1230 $this->doClearCache( $paths );
1234 * Clears any additional stat caches for storage paths
1236 * @see FileBackend::clearCache()
1238 * @param $paths Array Storage paths (optional)
1241 protected function doClearCache( array $paths = null ) {}
1244 * Is this a key/value store where directories are just virtual?
1245 * Virtual directories exists in so much as files exists that are
1246 * prefixed with the directory path followed by a forward slash.
1250 abstract protected function directoriesAreVirtual();
1253 * Check if a container name is valid.
1254 * This checks for for length and illegal characters.
1256 * @param $container string
1259 final protected static function isValidContainerName( $container ) {
1260 // This accounts for Swift and S3 restrictions while leaving room
1261 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1262 // This disallows directory separators or traversal characters.
1263 // Note that matching strings URL encode to the same string;
1264 // in Swift, the length restriction is *after* URL encoding.
1265 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1269 * Splits a storage path into an internal container name,
1270 * an internal relative file name, and a container shard suffix.
1271 * Any shard suffix is already appended to the internal container name.
1272 * This also checks that the storage path is valid and within this backend.
1274 * If the container is sharded but a suffix could not be determined,
1275 * this means that the path can only refer to a directory and can only
1276 * be scanned by looking in all the container shards.
1278 * @param $storagePath string
1279 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1281 final protected function resolveStoragePath( $storagePath ) {
1282 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1283 if ( $backend === $this->name
) { // must be for this backend
1284 $relPath = self
::normalizeContainerPath( $relPath );
1285 if ( $relPath !== null ) {
1286 // Get shard for the normalized path if this container is sharded
1287 $cShard = $this->getContainerShard( $container, $relPath );
1288 // Validate and sanitize the relative path (backend-specific)
1289 $relPath = $this->resolveContainerPath( $container, $relPath );
1290 if ( $relPath !== null ) {
1291 // Prepend any wiki ID prefix to the container name
1292 $container = $this->fullContainerName( $container );
1293 if ( self
::isValidContainerName( $container ) ) {
1294 // Validate and sanitize the container name (backend-specific)
1295 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1296 if ( $container !== null ) {
1297 return array( $container, $relPath, $cShard );
1303 return array( null, null, null );
1307 * Like resolveStoragePath() except null values are returned if
1308 * the container is sharded and the shard could not be determined.
1310 * @see FileBackendStore::resolveStoragePath()
1312 * @param $storagePath string
1313 * @return Array (container, path) or (null, null) if invalid
1315 final protected function resolveStoragePathReal( $storagePath ) {
1316 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1317 if ( $cShard !== null ) {
1318 return array( $container, $relPath );
1320 return array( null, null );
1324 * Get the container name shard suffix for a given path.
1325 * Any empty suffix means the container is not sharded.
1327 * @param $container string Container name
1328 * @param $relPath string Storage path relative to the container
1329 * @return string|null Returns null if shard could not be determined
1331 final protected function getContainerShard( $container, $relPath ) {
1332 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1333 if ( $levels == 1 ||
$levels == 2 ) {
1334 // Hash characters are either base 16 or 36
1335 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1336 // Get a regex that represents the shard portion of paths.
1337 // The concatenation of the captures gives us the shard.
1338 if ( $levels === 1 ) { // 16 or 36 shards per container
1339 $hashDirRegex = '(' . $char . ')';
1340 } else { // 256 or 1296 shards per container
1341 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1342 $hashDirRegex = $char . '/(' . $char . '{2})';
1343 } else { // short hash dir format (e.g. "a/b/c")
1344 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1347 // Allow certain directories to be above the hash dirs so as
1348 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1349 // They must be 2+ chars to avoid any hash directory ambiguity.
1351 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1352 return '.' . implode( '', array_slice( $m, 1 ) );
1354 return null; // failed to match
1356 return ''; // no sharding
1360 * Check if a storage path maps to a single shard.
1361 * Container dirs like "a", where the container shards on "x/xy",
1362 * can reside on several shards. Such paths are tricky to handle.
1364 * @param $storagePath string Storage path
1367 final public function isSingleShardPathInternal( $storagePath ) {
1368 list( $c, $r, $shard ) = $this->resolveStoragePath( $storagePath );
1369 return ( $shard !== null );
1373 * Get the sharding config for a container.
1374 * If greater than 0, then all file storage paths within
1375 * the container are required to be hashed accordingly.
1377 * @param $container string
1378 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
1380 final protected function getContainerHashLevels( $container ) {
1381 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1382 $config = $this->shardViaHashLevels
[$container];
1383 $hashLevels = (int)$config['levels'];
1384 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1385 $hashBase = (int)$config['base'];
1386 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1387 return array( $hashLevels, $hashBase, $config['repeat'] );
1391 return array( 0, 0, false ); // no sharding
1395 * Get a list of full container shard suffixes for a container
1397 * @param $container string
1400 final protected function getContainerSuffixes( $container ) {
1402 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1403 if ( $digits > 0 ) {
1404 $numShards = pow( $base, $digits );
1405 for ( $index = 0; $index < $numShards; $index++
) {
1406 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1413 * Get the full container name, including the wiki ID prefix
1415 * @param $container string
1418 final protected function fullContainerName( $container ) {
1419 if ( $this->wikiId
!= '' ) {
1420 return "{$this->wikiId}-$container";
1427 * Resolve a container name, checking if it's allowed by the backend.
1428 * This is intended for internal use, such as encoding illegal chars.
1429 * Subclasses can override this to be more restrictive.
1431 * @param $container string
1432 * @return string|null
1434 protected function resolveContainerName( $container ) {
1439 * Resolve a relative storage path, checking if it's allowed by the backend.
1440 * This is intended for internal use, such as encoding illegal chars or perhaps
1441 * getting absolute paths (e.g. FS based backends). Note that the relative path
1442 * may be the empty string (e.g. the path is simply to the container).
1444 * @param $container string Container name
1445 * @param $relStoragePath string Storage path relative to the container
1446 * @return string|null Path or null if not valid
1448 protected function resolveContainerPath( $container, $relStoragePath ) {
1449 return $relStoragePath;
1453 * Get the cache key for a container
1455 * @param $container string Resolved container name
1458 private function containerCacheKey( $container ) {
1459 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1463 * Set the cached info for a container
1465 * @param $container string Resolved container name
1466 * @param $val mixed Information to cache
1468 final protected function setContainerCache( $container, $val ) {
1469 $this->memCache
->add( $this->containerCacheKey( $container ), $val, 14*86400 );
1473 * Delete the cached info for a container.
1474 * The cache key is salted for a while to prevent race conditions.
1476 * @param $container string Resolved container name
1478 final protected function deleteContainerCache( $container ) {
1479 if ( !$this->memCache
->set( $this->containerCacheKey( $container ), 'PURGED', 300 ) ) {
1480 trigger_error( "Unable to delete stat cache for container $container." );
1485 * Do a batch lookup from cache for container stats for all containers
1486 * used in a list of container names, storage paths, or FileOp objects.
1487 * This loads the persistent cache values into the process cache.
1489 * @param $items Array
1492 final protected function primeContainerCache( array $items ) {
1493 wfProfileIn( __METHOD__
);
1494 wfProfileIn( __METHOD__
. '-' . $this->name
);
1496 $paths = array(); // list of storage paths
1497 $contNames = array(); // (cache key => resolved container name)
1498 // Get all the paths/containers from the items...
1499 foreach ( $items as $item ) {
1500 if ( $item instanceof FileOp
) {
1501 $paths = array_merge( $paths, $item->storagePathsRead() );
1502 $paths = array_merge( $paths, $item->storagePathsChanged() );
1503 } elseif ( self
::isStoragePath( $item ) ) {
1505 } elseif ( is_string( $item ) ) { // full container name
1506 $contNames[$this->containerCacheKey( $item )] = $item;
1509 // Get all the corresponding cache keys for paths...
1510 foreach ( $paths as $path ) {
1511 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1512 if ( $fullCont !== null ) { // valid path for this backend
1513 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1517 $contInfo = array(); // (resolved container name => cache value)
1518 // Get all cache entries for these container cache keys...
1519 $values = $this->memCache
->getMulti( array_keys( $contNames ) );
1520 foreach ( $values as $cacheKey => $val ) {
1521 $contInfo[$contNames[$cacheKey]] = $val;
1524 // Populate the container process cache for the backend...
1525 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1527 wfProfileOut( __METHOD__
. '-' . $this->name
);
1528 wfProfileOut( __METHOD__
);
1532 * Fill the backend-specific process cache given an array of
1533 * resolved container names and their corresponding cached info.
1534 * Only containers that actually exist should appear in the map.
1536 * @param $containerInfo Array Map of resolved container names to cached info
1539 protected function doPrimeContainerCache( array $containerInfo ) {}
1542 * Get the cache key for a file path
1544 * @param $path string Normalized storage path
1547 private function fileCacheKey( $path ) {
1548 return wfMemcKey( 'backend', $this->getName(), 'file', sha1( $path ) );
1552 * Set the cached stat info for a file path.
1553 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1554 * salting for the case when a file is created at a path were there was none before.
1556 * @param $path string Storage path
1557 * @param $val mixed Information to cache
1559 final protected function setFileCache( $path, $val ) {
1560 $path = FileBackend
::normalizeStoragePath( $path );
1561 if ( $path === null ) {
1562 return; // invalid storage path
1564 $this->memCache
->add( $this->fileCacheKey( $path ), $val, 7*86400 );
1568 * Delete the cached stat info for a file path.
1569 * The cache key is salted for a while to prevent race conditions.
1571 * @param $path string Storage path
1573 final protected function deleteFileCache( $path ) {
1574 $path = FileBackend
::normalizeStoragePath( $path );
1575 if ( $path === null ) {
1576 return; // invalid storage path
1578 if ( !$this->memCache
->set( $this->fileCacheKey( $path ), 'PURGED', 300 ) ) {
1579 trigger_error( "Unable to delete stat cache for file $path." );
1584 * Do a batch lookup from cache for file stats for all paths
1585 * used in a list of storage paths or FileOp objects.
1586 * This loads the persistent cache values into the process cache.
1588 * @param $items Array List of storage paths or FileOps
1591 final protected function primeFileCache( array $items ) {
1592 wfProfileIn( __METHOD__
);
1593 wfProfileIn( __METHOD__
. '-' . $this->name
);
1595 $paths = array(); // list of storage paths
1596 $pathNames = array(); // (cache key => storage path)
1597 // Get all the paths/containers from the items...
1598 foreach ( $items as $item ) {
1599 if ( $item instanceof FileOp
) {
1600 $paths = array_merge( $paths, $item->storagePathsRead() );
1601 $paths = array_merge( $paths, $item->storagePathsChanged() );
1602 } elseif ( self
::isStoragePath( $item ) ) {
1603 $paths[] = FileBackend
::normalizeStoragePath( $item );
1606 // Get rid of any paths that failed normalization...
1607 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1608 // Get all the corresponding cache keys for paths...
1609 foreach ( $paths as $path ) {
1610 list( $cont, $rel, $s ) = $this->resolveStoragePath( $path );
1611 if ( $rel !== null ) { // valid path for this backend
1612 $pathNames[$this->fileCacheKey( $path )] = $path;
1615 // Get all cache entries for these container cache keys...
1616 $values = $this->memCache
->getMulti( array_keys( $pathNames ) );
1617 foreach ( $values as $cacheKey => $val ) {
1618 if ( is_array( $val ) ) {
1619 $path = $pathNames[$cacheKey];
1620 $this->cheapCache
->set( $path, 'stat', $val );
1621 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1622 $this->cheapCache
->set( $path, 'sha1',
1623 array( 'hash' => $val['sha1'], 'latest' => $val['latest'] ) );
1628 wfProfileOut( __METHOD__
. '-' . $this->name
);
1629 wfProfileOut( __METHOD__
);
1633 * Set the 'concurrency' option from a list of operation options
1635 * @param $opts array Map of operation options
1638 final protected function setConcurrencyFlags( array $opts ) {
1639 $opts['concurrency'] = 1; // off
1640 if ( $this->parallelize
=== 'implicit' ) {
1641 if ( !isset( $opts['parallelize'] ) ||
$opts['parallelize'] ) {
1642 $opts['concurrency'] = $this->concurrency
;
1644 } elseif ( $this->parallelize
=== 'explicit' ) {
1645 if ( !empty( $opts['parallelize'] ) ) {
1646 $opts['concurrency'] = $this->concurrency
;
1654 * FileBackendStore helper class for performing asynchronous file operations.
1656 * For example, calling FileBackendStore::createInternal() with the "async"
1657 * param flag may result in a Status that contains this object as a value.
1658 * This class is largely backend-specific and is mostly just "magic" to be
1659 * passed to FileBackendStore::executeOpHandlesInternal().
1661 abstract class FileBackendStoreOpHandle
{
1663 public $params = array(); // params to caller functions
1664 /** @var FileBackendStore */
1667 public $resourcesToClose = array();
1669 public $call; // string; name that identifies the function called
1672 * Close all open file handles
1676 public function closeResources() {
1677 array_map( 'fclose', $this->resourcesToClose
);
1682 * FileBackendStore helper function to handle listings that span container shards.
1683 * Do not use this class from places outside of FileBackendStore.
1685 * @ingroup FileBackend
1687 abstract class FileBackendStoreShardListIterator
implements Iterator
{
1688 /** @var FileBackendStore */
1693 protected $shardSuffixes;
1694 protected $container; // string; full container name
1695 protected $directory; // string; resolved relative path
1697 /** @var Traversable */
1699 protected $curShard = 0; // integer
1700 protected $pos = 0; // integer
1703 protected $multiShardPaths = array(); // (rel path => 1)
1706 * @param $backend FileBackendStore
1707 * @param $container string Full storage container name
1708 * @param $dir string Storage directory relative to container
1709 * @param $suffixes Array List of container shard suffixes
1710 * @param $params Array
1712 public function __construct(
1713 FileBackendStore
$backend, $container, $dir, array $suffixes, array $params
1715 $this->backend
= $backend;
1716 $this->container
= $container;
1717 $this->directory
= $dir;
1718 $this->shardSuffixes
= $suffixes;
1719 $this->params
= $params;
1723 * @see Iterator::key()
1726 public function key() {
1731 * @see Iterator::valid()
1734 public function valid() {
1735 if ( $this->iter
instanceof Iterator
) {
1736 return $this->iter
->valid();
1737 } elseif ( is_array( $this->iter
) ) {
1738 return ( current( $this->iter
) !== false ); // no paths can have this value
1740 return false; // some failure?
1744 * @see Iterator::current()
1745 * @return string|bool String or false
1747 public function current() {
1748 return ( $this->iter
instanceof Iterator
)
1749 ?
$this->iter
->current()
1750 : current( $this->iter
);
1754 * @see Iterator::next()
1757 public function next() {
1759 ( $this->iter
instanceof Iterator
) ?
$this->iter
->next() : next( $this->iter
);
1761 $continue = false; // keep scanning shards?
1762 $this->filterViaNext(); // filter out duplicates
1763 // Find the next non-empty shard if no elements are left
1764 if ( !$this->valid() ) {
1765 $this->nextShardIteratorIfNotValid();
1766 $continue = $this->valid(); // re-filter unless we ran out of shards
1768 } while ( $continue );
1772 * @see Iterator::rewind()
1775 public function rewind() {
1777 $this->curShard
= 0;
1778 $this->setIteratorFromCurrentShard();
1780 $continue = false; // keep scanning shards?
1781 $this->filterViaNext(); // filter out duplicates
1782 // Find the next non-empty shard if no elements are left
1783 if ( !$this->valid() ) {
1784 $this->nextShardIteratorIfNotValid();
1785 $continue = $this->valid(); // re-filter unless we ran out of shards
1787 } while ( $continue );
1791 * Filter out duplicate items by advancing to the next ones
1793 protected function filterViaNext() {
1794 while ( $this->valid() ) {
1795 $rel = $this->iter
->current(); // path relative to given directory
1796 $path = $this->params
['dir'] . "/{$rel}"; // full storage path
1797 if ( $this->backend
->isSingleShardPathInternal( $path ) ) {
1798 break; // path is only on one shard; no issue with duplicates
1799 } elseif ( isset( $this->multiShardPaths
[$rel] ) ) {
1800 // Don't keep listing paths that are on multiple shards
1801 ( $this->iter
instanceof Iterator
) ?
$this->iter
->next() : next( $this->iter
);
1803 $this->multiShardPaths
[$rel] = 1;
1810 * If the list iterator for this container shard is out of items,
1811 * then move on to the next container that has items.
1812 * If there are none, then it advances to the last container.
1814 protected function nextShardIteratorIfNotValid() {
1815 while ( !$this->valid() && ++
$this->curShard
< count( $this->shardSuffixes
) ) {
1816 $this->setIteratorFromCurrentShard();
1821 * Set the list iterator to that of the current container shard
1823 protected function setIteratorFromCurrentShard() {
1824 $this->iter
= $this->listFromShard(
1825 $this->container
. $this->shardSuffixes
[$this->curShard
],
1826 $this->directory
, $this->params
);
1827 // Start loading results so that current() works
1828 if ( $this->iter
) {
1829 ( $this->iter
instanceof Iterator
) ?
$this->iter
->rewind() : reset( $this->iter
);
1834 * Get the list for a given container shard
1836 * @param $container string Resolved container name
1837 * @param $dir string Resolved path relative to container
1838 * @param $params Array
1839 * @return Traversable|Array|null
1841 abstract protected function listFromShard( $container, $dir, array $params );
1845 * Iterator for listing directories
1847 class FileBackendStoreShardDirIterator
extends FileBackendStoreShardListIterator
{
1849 * @see FileBackendStoreShardListIterator::listFromShard()
1850 * @return Array|null|Traversable
1852 protected function listFromShard( $container, $dir, array $params ) {
1853 return $this->backend
->getDirectoryListInternal( $container, $dir, $params );
1858 * Iterator for listing regular files
1860 class FileBackendStoreShardFileIterator
extends FileBackendStoreShardListIterator
{
1862 * @see FileBackendStoreShardListIterator::listFromShard()
1863 * @return Array|null|Traversable
1865 protected function listFromShard( $container, $dir, array $params ) {
1866 return $this->backend
->getFileListInternal( $container, $dir, $params );