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' );
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.
1011 * @param $performOps Array List of FileOp objects
1012 * @return Array ('sh' => list of paths, 'ex' => list of paths)
1014 final public function getPathsToLockForOpsInternal( array $performOps ) {
1015 // Build up a list of files to lock...
1016 $paths = array( 'sh' => array(), 'ex' => array() );
1017 foreach ( $performOps as $fileOp ) {
1018 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1019 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1021 // Optimization: if doing an EX lock anyway, don't also set an SH one
1022 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1023 // Get a shared lock on the parent directory of each path changed
1024 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1030 * @see FileBackend::getScopedLocksForOps()
1033 public function getScopedLocksForOps( array $ops, Status
$status ) {
1034 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1036 $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status ),
1037 $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status )
1042 * @see FileBackend::doOperationsInternal()
1045 final protected function doOperationsInternal( array $ops, array $opts ) {
1046 wfProfileIn( __METHOD__
);
1047 wfProfileIn( __METHOD__
. '-' . $this->name
);
1048 $status = Status
::newGood();
1050 // Build up a list of FileOps...
1051 $performOps = $this->getOperationsInternal( $ops );
1053 // Acquire any locks as needed...
1054 if ( empty( $opts['nonLocking'] ) ) {
1055 // Build up a list of files to lock...
1056 $paths = $this->getPathsToLockForOpsInternal( $performOps );
1057 // Try to lock those files for the scope of this function...
1058 $scopeLockS = $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status );
1059 $scopeLockE = $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status );
1060 if ( !$status->isOK() ) {
1061 wfProfileOut( __METHOD__
. '-' . $this->name
);
1062 wfProfileOut( __METHOD__
);
1063 return $status; // abort
1067 // Clear any file cache entries (after locks acquired)
1068 if ( empty( $opts['preserveCache'] ) ) {
1069 $this->clearCache();
1072 // Load from the persistent file and container caches
1073 $this->primeFileCache( $performOps );
1074 $this->primeContainerCache( $performOps );
1076 // Actually attempt the operation batch...
1077 $opts = $this->setConcurrencyFlags( $opts );
1078 $subStatus = FileOpBatch
::attempt( $performOps, $opts, $this->fileJournal
);
1080 // Merge errors into status fields
1081 $status->merge( $subStatus );
1082 $status->success
= $subStatus->success
; // not done in merge()
1084 wfProfileOut( __METHOD__
. '-' . $this->name
);
1085 wfProfileOut( __METHOD__
);
1090 * @see FileBackend::doQuickOperationsInternal()
1092 * @throws MWException
1094 final protected function doQuickOperationsInternal( array $ops ) {
1095 wfProfileIn( __METHOD__
);
1096 wfProfileIn( __METHOD__
. '-' . $this->name
);
1097 $status = Status
::newGood();
1099 $supportedOps = array( 'create', 'store', 'copy', 'move', 'delete', 'null' );
1100 $async = ( $this->parallelize
=== 'implicit' );
1101 $maxConcurrency = $this->concurrency
; // throttle
1103 $statuses = array(); // array of (index => Status)
1104 $fileOpHandles = array(); // list of (index => handle) arrays
1105 $curFileOpHandles = array(); // current handle batch
1106 // Perform the sync-only ops and build up op handles for the async ops...
1107 foreach ( $ops as $index => $params ) {
1108 if ( !in_array( $params['op'], $supportedOps ) ) {
1109 wfProfileOut( __METHOD__
. '-' . $this->name
);
1110 wfProfileOut( __METHOD__
);
1111 throw new MWException( "Operation '{$params['op']}' is not supported." );
1113 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1114 $subStatus = $this->$method( array( 'async' => $async ) +
$params );
1115 if ( $subStatus->value
instanceof FileBackendStoreOpHandle
) { // async
1116 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1117 $fileOpHandles[] = $curFileOpHandles; // push this batch
1118 $curFileOpHandles = array();
1120 $curFileOpHandles[$index] = $subStatus->value
; // keep index
1121 } else { // error or completed
1122 $statuses[$index] = $subStatus; // keep index
1125 if ( count( $curFileOpHandles ) ) {
1126 $fileOpHandles[] = $curFileOpHandles; // last batch
1128 // Do all the async ops that can be done concurrently...
1129 foreach ( $fileOpHandles as $fileHandleBatch ) {
1130 $statuses = $statuses +
$this->executeOpHandlesInternal( $fileHandleBatch );
1132 // Marshall and merge all the responses...
1133 foreach ( $statuses as $index => $subStatus ) {
1134 $status->merge( $subStatus );
1135 if ( $subStatus->isOK() ) {
1136 $status->success
[$index] = true;
1137 ++
$status->successCount
;
1139 $status->success
[$index] = false;
1140 ++
$status->failCount
;
1144 wfProfileOut( __METHOD__
. '-' . $this->name
);
1145 wfProfileOut( __METHOD__
);
1150 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1151 * The resulting Status object fields will correspond
1152 * to the order in which the handles where given.
1154 * @param $handles Array List of FileBackendStoreOpHandle objects
1155 * @return Array Map of Status objects
1156 * @throws MWException
1158 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1159 wfProfileIn( __METHOD__
);
1160 wfProfileIn( __METHOD__
. '-' . $this->name
);
1161 foreach ( $fileOpHandles as $fileOpHandle ) {
1162 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle
) ) {
1163 throw new MWException( "Given a non-FileBackendStoreOpHandle object." );
1164 } elseif ( $fileOpHandle->backend
->getName() !== $this->getName() ) {
1165 throw new MWException( "Given a FileBackendStoreOpHandle for the wrong backend." );
1168 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1169 foreach ( $fileOpHandles as $fileOpHandle ) {
1170 $fileOpHandle->closeResources();
1172 wfProfileOut( __METHOD__
. '-' . $this->name
);
1173 wfProfileOut( __METHOD__
);
1178 * @see FileBackendStore::executeOpHandlesInternal()
1179 * @return Array List of corresponding Status objects
1181 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1182 foreach ( $fileOpHandles as $fileOpHandle ) { // OK if empty
1183 throw new MWException( "This backend supports no asynchronous operations." );
1189 * @see FileBackend::preloadCache()
1191 final public function preloadCache( array $paths ) {
1192 $fullConts = array(); // full container names
1193 foreach ( $paths as $path ) {
1194 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1195 $fullConts[] = $fullCont;
1197 // Load from the persistent file and container caches
1198 $this->primeContainerCache( $fullConts );
1199 $this->primeFileCache( $paths );
1203 * @see FileBackend::clearCache()
1205 final public function clearCache( array $paths = null ) {
1206 if ( is_array( $paths ) ) {
1207 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1208 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1210 if ( $paths === null ) {
1211 $this->cheapCache
->clear();
1212 $this->expensiveCache
->clear();
1214 foreach ( $paths as $path ) {
1215 $this->cheapCache
->clear( $path );
1216 $this->expensiveCache
->clear( $path );
1219 $this->doClearCache( $paths );
1223 * Clears any additional stat caches for storage paths
1225 * @see FileBackend::clearCache()
1227 * @param $paths Array Storage paths (optional)
1230 protected function doClearCache( array $paths = null ) {}
1233 * Is this a key/value store where directories are just virtual?
1234 * Virtual directories exists in so much as files exists that are
1235 * prefixed with the directory path followed by a forward slash.
1239 abstract protected function directoriesAreVirtual();
1242 * Check if a container name is valid.
1243 * This checks for for length and illegal characters.
1245 * @param $container string
1248 final protected static function isValidContainerName( $container ) {
1249 // This accounts for Swift and S3 restrictions while leaving room
1250 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1251 // This disallows directory separators or traversal characters.
1252 // Note that matching strings URL encode to the same string;
1253 // in Swift, the length restriction is *after* URL encoding.
1254 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1258 * Splits a storage path into an internal container name,
1259 * an internal relative file name, and a container shard suffix.
1260 * Any shard suffix is already appended to the internal container name.
1261 * This also checks that the storage path is valid and within this backend.
1263 * If the container is sharded but a suffix could not be determined,
1264 * this means that the path can only refer to a directory and can only
1265 * be scanned by looking in all the container shards.
1267 * @param $storagePath string
1268 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1270 final protected function resolveStoragePath( $storagePath ) {
1271 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1272 if ( $backend === $this->name
) { // must be for this backend
1273 $relPath = self
::normalizeContainerPath( $relPath );
1274 if ( $relPath !== null ) {
1275 // Get shard for the normalized path if this container is sharded
1276 $cShard = $this->getContainerShard( $container, $relPath );
1277 // Validate and sanitize the relative path (backend-specific)
1278 $relPath = $this->resolveContainerPath( $container, $relPath );
1279 if ( $relPath !== null ) {
1280 // Prepend any wiki ID prefix to the container name
1281 $container = $this->fullContainerName( $container );
1282 if ( self
::isValidContainerName( $container ) ) {
1283 // Validate and sanitize the container name (backend-specific)
1284 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1285 if ( $container !== null ) {
1286 return array( $container, $relPath, $cShard );
1292 return array( null, null, null );
1296 * Like resolveStoragePath() except null values are returned if
1297 * the container is sharded and the shard could not be determined.
1299 * @see FileBackendStore::resolveStoragePath()
1301 * @param $storagePath string
1302 * @return Array (container, path) or (null, null) if invalid
1304 final protected function resolveStoragePathReal( $storagePath ) {
1305 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1306 if ( $cShard !== null ) {
1307 return array( $container, $relPath );
1309 return array( null, null );
1313 * Get the container name shard suffix for a given path.
1314 * Any empty suffix means the container is not sharded.
1316 * @param $container string Container name
1317 * @param $relPath string Storage path relative to the container
1318 * @return string|null Returns null if shard could not be determined
1320 final protected function getContainerShard( $container, $relPath ) {
1321 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1322 if ( $levels == 1 ||
$levels == 2 ) {
1323 // Hash characters are either base 16 or 36
1324 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1325 // Get a regex that represents the shard portion of paths.
1326 // The concatenation of the captures gives us the shard.
1327 if ( $levels === 1 ) { // 16 or 36 shards per container
1328 $hashDirRegex = '(' . $char . ')';
1329 } else { // 256 or 1296 shards per container
1330 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1331 $hashDirRegex = $char . '/(' . $char . '{2})';
1332 } else { // short hash dir format (e.g. "a/b/c")
1333 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1336 // Allow certain directories to be above the hash dirs so as
1337 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1338 // They must be 2+ chars to avoid any hash directory ambiguity.
1340 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1341 return '.' . implode( '', array_slice( $m, 1 ) );
1343 return null; // failed to match
1345 return ''; // no sharding
1349 * Check if a storage path maps to a single shard.
1350 * Container dirs like "a", where the container shards on "x/xy",
1351 * can reside on several shards. Such paths are tricky to handle.
1353 * @param $storagePath string Storage path
1356 final public function isSingleShardPathInternal( $storagePath ) {
1357 list( $c, $r, $shard ) = $this->resolveStoragePath( $storagePath );
1358 return ( $shard !== null );
1362 * Get the sharding config for a container.
1363 * If greater than 0, then all file storage paths within
1364 * the container are required to be hashed accordingly.
1366 * @param $container string
1367 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
1369 final protected function getContainerHashLevels( $container ) {
1370 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1371 $config = $this->shardViaHashLevels
[$container];
1372 $hashLevels = (int)$config['levels'];
1373 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1374 $hashBase = (int)$config['base'];
1375 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1376 return array( $hashLevels, $hashBase, $config['repeat'] );
1380 return array( 0, 0, false ); // no sharding
1384 * Get a list of full container shard suffixes for a container
1386 * @param $container string
1389 final protected function getContainerSuffixes( $container ) {
1391 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1392 if ( $digits > 0 ) {
1393 $numShards = pow( $base, $digits );
1394 for ( $index = 0; $index < $numShards; $index++
) {
1395 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1402 * Get the full container name, including the wiki ID prefix
1404 * @param $container string
1407 final protected function fullContainerName( $container ) {
1408 if ( $this->wikiId
!= '' ) {
1409 return "{$this->wikiId}-$container";
1416 * Resolve a container name, checking if it's allowed by the backend.
1417 * This is intended for internal use, such as encoding illegal chars.
1418 * Subclasses can override this to be more restrictive.
1420 * @param $container string
1421 * @return string|null
1423 protected function resolveContainerName( $container ) {
1428 * Resolve a relative storage path, checking if it's allowed by the backend.
1429 * This is intended for internal use, such as encoding illegal chars or perhaps
1430 * getting absolute paths (e.g. FS based backends). Note that the relative path
1431 * may be the empty string (e.g. the path is simply to the container).
1433 * @param $container string Container name
1434 * @param $relStoragePath string Storage path relative to the container
1435 * @return string|null Path or null if not valid
1437 protected function resolveContainerPath( $container, $relStoragePath ) {
1438 return $relStoragePath;
1442 * Get the cache key for a container
1444 * @param $container string Resolved container name
1447 private function containerCacheKey( $container ) {
1448 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1452 * Set the cached info for a container
1454 * @param $container string Resolved container name
1455 * @param $val mixed Information to cache
1457 final protected function setContainerCache( $container, $val ) {
1458 $this->memCache
->add( $this->containerCacheKey( $container ), $val, 14*86400 );
1462 * Delete the cached info for a container.
1463 * The cache key is salted for a while to prevent race conditions.
1465 * @param $container string Resolved container name
1467 final protected function deleteContainerCache( $container ) {
1468 if ( !$this->memCache
->set( $this->containerCacheKey( $container ), 'PURGED', 300 ) ) {
1469 trigger_error( "Unable to delete stat cache for container $container." );
1474 * Do a batch lookup from cache for container stats for all containers
1475 * used in a list of container names, storage paths, or FileOp objects.
1477 * @param $items Array
1480 final protected function primeContainerCache( array $items ) {
1481 wfProfileIn( __METHOD__
);
1482 wfProfileIn( __METHOD__
. '-' . $this->name
);
1484 $paths = array(); // list of storage paths
1485 $contNames = array(); // (cache key => resolved container name)
1486 // Get all the paths/containers from the items...
1487 foreach ( $items as $item ) {
1488 if ( $item instanceof FileOp
) {
1489 $paths = array_merge( $paths, $item->storagePathsRead() );
1490 $paths = array_merge( $paths, $item->storagePathsChanged() );
1491 } elseif ( self
::isStoragePath( $item ) ) {
1493 } elseif ( is_string( $item ) ) { // full container name
1494 $contNames[$this->containerCacheKey( $item )] = $item;
1497 // Get all the corresponding cache keys for paths...
1498 foreach ( $paths as $path ) {
1499 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1500 if ( $fullCont !== null ) { // valid path for this backend
1501 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1505 $contInfo = array(); // (resolved container name => cache value)
1506 // Get all cache entries for these container cache keys...
1507 $values = $this->memCache
->getMulti( array_keys( $contNames ) );
1508 foreach ( $values as $cacheKey => $val ) {
1509 $contInfo[$contNames[$cacheKey]] = $val;
1512 // Populate the container process cache for the backend...
1513 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1515 wfProfileOut( __METHOD__
. '-' . $this->name
);
1516 wfProfileOut( __METHOD__
);
1520 * Fill the backend-specific process cache given an array of
1521 * resolved container names and their corresponding cached info.
1522 * Only containers that actually exist should appear in the map.
1524 * @param $containerInfo Array Map of resolved container names to cached info
1527 protected function doPrimeContainerCache( array $containerInfo ) {}
1530 * Get the cache key for a file path
1532 * @param $path string Storage path
1535 private function fileCacheKey( $path ) {
1536 return wfMemcKey( 'backend', $this->getName(), 'file', sha1( $path ) );
1540 * Set the cached stat info for a file path.
1541 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1542 * salting for the case when a file is created at a path were there was none before.
1544 * @param $path string Storage path
1545 * @param $val mixed Information to cache
1547 final protected function setFileCache( $path, $val ) {
1548 $this->memCache
->add( $this->fileCacheKey( $path ), $val, 7*86400 );
1552 * Delete the cached stat info for a file path.
1553 * The cache key is salted for a while to prevent race conditions.
1555 * @param $path string Storage path
1557 final protected function deleteFileCache( $path ) {
1558 if ( !$this->memCache
->set( $this->fileCacheKey( $path ), 'PURGED', 300 ) ) {
1559 trigger_error( "Unable to delete stat cache for file $path." );
1564 * Do a batch lookup from cache for file stats for all paths
1565 * used in a list of storage paths or FileOp objects.
1567 * @param $items Array List of storage paths or FileOps
1570 final protected function primeFileCache( array $items ) {
1571 wfProfileIn( __METHOD__
);
1572 wfProfileIn( __METHOD__
. '-' . $this->name
);
1574 $paths = array(); // list of storage paths
1575 $pathNames = array(); // (cache key => storage path)
1576 // Get all the paths/containers from the items...
1577 foreach ( $items as $item ) {
1578 if ( $item instanceof FileOp
) {
1579 $paths = array_merge( $paths, $item->storagePathsRead() );
1580 $paths = array_merge( $paths, $item->storagePathsChanged() );
1581 } elseif ( self
::isStoragePath( $item ) ) {
1585 // Get all the corresponding cache keys for paths...
1586 foreach ( $paths as $path ) {
1587 list( $cont, $rel, $s ) = $this->resolveStoragePath( $path );
1588 if ( $rel !== null ) { // valid path for this backend
1589 $pathNames[$this->fileCacheKey( $path )] = $path;
1592 // Get all cache entries for these container cache keys...
1593 $values = $this->memCache
->getMulti( array_keys( $pathNames ) );
1594 foreach ( $values as $cacheKey => $val ) {
1595 if ( is_array( $val ) ) {
1596 $path = $pathNames[$cacheKey];
1597 $this->cheapCache
->set( $path, 'stat', $val );
1598 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1599 $this->cheapCache
->set( $path, 'sha1',
1600 array( 'hash' => $val['sha1'], 'latest' => $val['latest'] ) );
1605 wfProfileOut( __METHOD__
. '-' . $this->name
);
1606 wfProfileOut( __METHOD__
);
1610 * Set the 'concurrency' option from a list of operation options
1612 * @param $opts array Map of operation options
1615 final protected function setConcurrencyFlags( array $opts ) {
1616 $opts['concurrency'] = 1; // off
1617 if ( $this->parallelize
=== 'implicit' ) {
1618 if ( !isset( $opts['parallelize'] ) ||
$opts['parallelize'] ) {
1619 $opts['concurrency'] = $this->concurrency
;
1621 } elseif ( $this->parallelize
=== 'explicit' ) {
1622 if ( !empty( $opts['parallelize'] ) ) {
1623 $opts['concurrency'] = $this->concurrency
;
1631 * FileBackendStore helper class for performing asynchronous file operations.
1633 * For example, calling FileBackendStore::createInternal() with the "async"
1634 * param flag may result in a Status that contains this object as a value.
1635 * This class is largely backend-specific and is mostly just "magic" to be
1636 * passed to FileBackendStore::executeOpHandlesInternal().
1638 abstract class FileBackendStoreOpHandle
{
1640 public $params = array(); // params to caller functions
1641 /** @var FileBackendStore */
1644 public $resourcesToClose = array();
1646 public $call; // string; name that identifies the function called
1649 * Close all open file handles
1653 public function closeResources() {
1654 array_map( 'fclose', $this->resourcesToClose
);
1659 * FileBackendStore helper function to handle listings that span container shards.
1660 * Do not use this class from places outside of FileBackendStore.
1662 * @ingroup FileBackend
1664 abstract class FileBackendStoreShardListIterator
implements Iterator
{
1665 /** @var FileBackendStore */
1670 protected $shardSuffixes;
1671 protected $container; // string; full container name
1672 protected $directory; // string; resolved relative path
1674 /** @var Traversable */
1676 protected $curShard = 0; // integer
1677 protected $pos = 0; // integer
1680 protected $multiShardPaths = array(); // (rel path => 1)
1683 * @param $backend FileBackendStore
1684 * @param $container string Full storage container name
1685 * @param $dir string Storage directory relative to container
1686 * @param $suffixes Array List of container shard suffixes
1687 * @param $params Array
1689 public function __construct(
1690 FileBackendStore
$backend, $container, $dir, array $suffixes, array $params
1692 $this->backend
= $backend;
1693 $this->container
= $container;
1694 $this->directory
= $dir;
1695 $this->shardSuffixes
= $suffixes;
1696 $this->params
= $params;
1700 * @see Iterator::key()
1703 public function key() {
1708 * @see Iterator::valid()
1711 public function valid() {
1712 if ( $this->iter
instanceof Iterator
) {
1713 return $this->iter
->valid();
1714 } elseif ( is_array( $this->iter
) ) {
1715 return ( current( $this->iter
) !== false ); // no paths can have this value
1717 return false; // some failure?
1721 * @see Iterator::current()
1722 * @return string|bool String or false
1724 public function current() {
1725 return ( $this->iter
instanceof Iterator
)
1726 ?
$this->iter
->current()
1727 : current( $this->iter
);
1731 * @see Iterator::next()
1734 public function next() {
1736 ( $this->iter
instanceof Iterator
) ?
$this->iter
->next() : next( $this->iter
);
1738 $continue = false; // keep scanning shards?
1739 $this->filterViaNext(); // filter out duplicates
1740 // Find the next non-empty shard if no elements are left
1741 if ( !$this->valid() ) {
1742 $this->nextShardIteratorIfNotValid();
1743 $continue = $this->valid(); // re-filter unless we ran out of shards
1745 } while ( $continue );
1749 * @see Iterator::rewind()
1752 public function rewind() {
1754 $this->curShard
= 0;
1755 $this->setIteratorFromCurrentShard();
1757 $continue = false; // keep scanning shards?
1758 $this->filterViaNext(); // filter out duplicates
1759 // Find the next non-empty shard if no elements are left
1760 if ( !$this->valid() ) {
1761 $this->nextShardIteratorIfNotValid();
1762 $continue = $this->valid(); // re-filter unless we ran out of shards
1764 } while ( $continue );
1768 * Filter out duplicate items by advancing to the next ones
1770 protected function filterViaNext() {
1771 while ( $this->valid() ) {
1772 $rel = $this->iter
->current(); // path relative to given directory
1773 $path = $this->params
['dir'] . "/{$rel}"; // full storage path
1774 if ( $this->backend
->isSingleShardPathInternal( $path ) ) {
1775 break; // path is only on one shard; no issue with duplicates
1776 } elseif ( isset( $this->multiShardPaths
[$rel] ) ) {
1777 // Don't keep listing paths that are on multiple shards
1778 ( $this->iter
instanceof Iterator
) ?
$this->iter
->next() : next( $this->iter
);
1780 $this->multiShardPaths
[$rel] = 1;
1787 * If the list iterator for this container shard is out of items,
1788 * then move on to the next container that has items.
1789 * If there are none, then it advances to the last container.
1791 protected function nextShardIteratorIfNotValid() {
1792 while ( !$this->valid() && ++
$this->curShard
< count( $this->shardSuffixes
) ) {
1793 $this->setIteratorFromCurrentShard();
1798 * Set the list iterator to that of the current container shard
1800 protected function setIteratorFromCurrentShard() {
1801 $this->iter
= $this->listFromShard(
1802 $this->container
. $this->shardSuffixes
[$this->curShard
],
1803 $this->directory
, $this->params
);
1804 // Start loading results so that current() works
1805 if ( $this->iter
) {
1806 ( $this->iter
instanceof Iterator
) ?
$this->iter
->rewind() : reset( $this->iter
);
1811 * Get the list for a given container shard
1813 * @param $container string Resolved container name
1814 * @param $dir string Resolved path relative to container
1815 * @param $params Array
1816 * @return Traversable|Array|null
1818 abstract protected function listFromShard( $container, $dir, array $params );
1822 * Iterator for listing directories
1824 class FileBackendStoreShardDirIterator
extends FileBackendStoreShardListIterator
{
1826 * @see FileBackendStoreShardListIterator::listFromShard()
1827 * @return Array|null|Traversable
1829 protected function listFromShard( $container, $dir, array $params ) {
1830 return $this->backend
->getDirectoryListInternal( $container, $dir, $params );
1835 * Iterator for listing regular files
1837 class FileBackendStoreShardFileIterator
extends FileBackendStoreShardListIterator
{
1839 * @see FileBackendStoreShardListIterator::listFromShard()
1840 * @return Array|null|Traversable
1842 protected function listFromShard( $container, $dir, array $params ) {
1843 return $this->backend
->getFileListInternal( $container, $dir, $params );