Merge "Update 'right-protect', 'right-autoconfirmed' messages"
[mediawiki.git] / includes / filebackend / FileBackendStore.php
blobe976a7aa9c8b0bb9eb02dcf854ced1cfe3dd38ce
1 <?php
2 /**
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
20 * @file
21 * @ingroup FileBackend
22 * @author Aaron Schulz
25 /**
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
36 * @since 1.19
38 abstract class FileBackendStore extends FileBackend {
39 /** @var BagOStuff */
40 protected $memCache;
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)
51 const CACHE_TTL = 10; // integer; TTL in seconds for process cache entries
52 const CACHE_CHEAP_SIZE = 300; // integer; max entries in "cheap cache"
53 const CACHE_EXPENSIVE_SIZE = 5; // integer; max entries in "expensive cache"
55 /**
56 * @see FileBackend::__construct()
58 * @param array $config
60 public function __construct( array $config ) {
61 parent::__construct( $config );
62 $this->memCache = new EmptyBagOStuff(); // disabled by default
63 $this->cheapCache = new ProcessCacheLRU( self::CACHE_CHEAP_SIZE );
64 $this->expensiveCache = new ProcessCacheLRU( self::CACHE_EXPENSIVE_SIZE );
67 /**
68 * Get the maximum allowable file size given backend
69 * medium restrictions and basic performance constraints.
70 * Do not call this function from places outside FileBackend and FileOp.
72 * @return integer Bytes
74 final public function maxFileSizeInternal() {
75 return $this->maxFileSize;
78 /**
79 * Check if a file can be created or changed at a given storage path.
80 * FS backends should check if the parent directory exists, files can be
81 * written under it, and that any file already there is writable.
82 * Backends using key/value stores should check if the container exists.
84 * @param string $storagePath
85 * @return bool
87 abstract public function isPathUsableInternal( $storagePath );
89 /**
90 * Create a file in the backend with the given contents.
91 * This will overwrite any file that exists at the destination.
92 * Do not call this function from places outside FileBackend and FileOp.
94 * $params include:
95 * - content : the raw file contents
96 * - dst : destination storage path
97 * - headers : HTTP header name/value map
98 * - async : Status will be returned immediately if supported.
99 * If the status is OK, then its value field will be
100 * set to a FileBackendStoreOpHandle object.
101 * - dstExists : Whether a file exists at the destination (optimization).
102 * Callers can use "false" if no existing file is being changed.
104 * @param array $params
105 * @return Status
107 final public function createInternal( array $params ) {
108 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
109 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
110 $status = Status::newFatal( 'backend-fail-maxsize',
111 $params['dst'], $this->maxFileSizeInternal() );
112 } else {
113 $status = $this->doCreateInternal( $params );
114 $this->clearCache( array( $params['dst'] ) );
115 if ( !isset( $params['dstExists'] ) || $params['dstExists'] ) {
116 $this->deleteFileCache( $params['dst'] ); // persistent cache
119 return $status;
123 * @see FileBackendStore::createInternal()
124 * @return Status
126 abstract protected function doCreateInternal( array $params );
129 * Store a file into the backend from a file on disk.
130 * This will overwrite any file that exists at the destination.
131 * Do not call this function from places outside FileBackend and FileOp.
133 * $params include:
134 * - src : source path on disk
135 * - dst : destination storage path
136 * - headers : HTTP header name/value map
137 * - async : Status will be returned immediately if supported.
138 * If the status is OK, then its value field will be
139 * set to a FileBackendStoreOpHandle object.
140 * - dstExists : Whether a file exists at the destination (optimization).
141 * Callers can use "false" if no existing file is being changed.
143 * @param array $params
144 * @return Status
146 final public function storeInternal( array $params ) {
147 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
148 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
149 $status = Status::newFatal( 'backend-fail-maxsize',
150 $params['dst'], $this->maxFileSizeInternal() );
151 } else {
152 $status = $this->doStoreInternal( $params );
153 $this->clearCache( array( $params['dst'] ) );
154 if ( !isset( $params['dstExists'] ) || $params['dstExists'] ) {
155 $this->deleteFileCache( $params['dst'] ); // persistent cache
158 return $status;
162 * @see FileBackendStore::storeInternal()
163 * @return Status
165 abstract protected function doStoreInternal( array $params );
168 * Copy a file from one storage path to another in the backend.
169 * This will overwrite any file that exists at the destination.
170 * Do not call this function from places outside FileBackend and FileOp.
172 * $params include:
173 * - src : source storage path
174 * - dst : destination storage path
175 * - ignoreMissingSource : do nothing if the source file does not exist
176 * - headers : HTTP header name/value map
177 * - async : Status will be returned immediately if supported.
178 * If the status is OK, then its value field will be
179 * set to a FileBackendStoreOpHandle object.
180 * - dstExists : Whether a file exists at the destination (optimization).
181 * Callers can use "false" if no existing file is being changed.
183 * @param array $params
184 * @return Status
186 final public function copyInternal( array $params ) {
187 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
188 $status = $this->doCopyInternal( $params );
189 $this->clearCache( array( $params['dst'] ) );
190 if ( !isset( $params['dstExists'] ) || $params['dstExists'] ) {
191 $this->deleteFileCache( $params['dst'] ); // persistent cache
193 return $status;
197 * @see FileBackendStore::copyInternal()
198 * @return Status
200 abstract protected function doCopyInternal( array $params );
203 * Delete a file at the storage path.
204 * Do not call this function from places outside FileBackend and FileOp.
206 * $params include:
207 * - src : source storage path
208 * - ignoreMissingSource : do nothing if the source file does not exist
209 * - async : Status will be returned immediately if supported.
210 * If the status is OK, then its value field will be
211 * set to a FileBackendStoreOpHandle object.
213 * @param array $params
214 * @return Status
216 final public function deleteInternal( array $params ) {
217 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
218 $status = $this->doDeleteInternal( $params );
219 $this->clearCache( array( $params['src'] ) );
220 $this->deleteFileCache( $params['src'] ); // persistent cache
221 return $status;
225 * @see FileBackendStore::deleteInternal()
226 * @return Status
228 abstract protected function doDeleteInternal( array $params );
231 * Move a file from one storage path to another in the backend.
232 * This will overwrite any file that exists at the destination.
233 * Do not call this function from places outside FileBackend and FileOp.
235 * $params include:
236 * - src : source storage path
237 * - dst : destination storage path
238 * - ignoreMissingSource : do nothing if the source file does not exist
239 * - headers : HTTP header name/value map
240 * - async : Status will be returned immediately if supported.
241 * If the status is OK, then its value field will be
242 * set to a FileBackendStoreOpHandle object.
243 * - dstExists : Whether a file exists at the destination (optimization).
244 * Callers can use "false" if no existing file is being changed.
246 * @param array $params
247 * @return Status
249 final public function moveInternal( array $params ) {
250 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
251 $status = $this->doMoveInternal( $params );
252 $this->clearCache( array( $params['src'], $params['dst'] ) );
253 $this->deleteFileCache( $params['src'] ); // persistent cache
254 if ( !isset( $params['dstExists'] ) || $params['dstExists'] ) {
255 $this->deleteFileCache( $params['dst'] ); // persistent cache
257 return $status;
261 * @see FileBackendStore::moveInternal()
262 * @return Status
264 protected function doMoveInternal( array $params ) {
265 unset( $params['async'] ); // two steps, won't work here :)
266 $nsrc = FileBackend::normalizeStoragePath( $params['src'] );
267 $ndst = FileBackend::normalizeStoragePath( $params['dst'] );
268 // Copy source to dest
269 $status = $this->copyInternal( $params );
270 if ( $nsrc !== $ndst && $status->isOK() ) {
271 // Delete source (only fails due to races or network problems)
272 $status->merge( $this->deleteInternal( array( 'src' => $params['src'] ) ) );
273 $status->setResult( true, $status->value ); // ignore delete() errors
275 return $status;
279 * Alter metadata for a file at the storage path.
280 * Do not call this function from places outside FileBackend and FileOp.
282 * $params include:
283 * - src : source storage path
284 * - headers : HTTP header name/value map
285 * - async : Status will be returned immediately if supported.
286 * If the status is OK, then its value field will be
287 * set to a FileBackendStoreOpHandle object.
289 * @param array $params
290 * @return Status
292 final public function describeInternal( array $params ) {
293 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
294 if ( count( $params['headers'] ) ) {
295 $status = $this->doDescribeInternal( $params );
296 $this->clearCache( array( $params['src'] ) );
297 $this->deleteFileCache( $params['src'] ); // persistent cache
298 } else {
299 $status = Status::newGood(); // nothing to do
301 return $status;
305 * @see FileBackendStore::describeInternal()
306 * @return Status
308 protected function doDescribeInternal( array $params ) {
309 return Status::newGood();
313 * No-op file operation that does nothing.
314 * Do not call this function from places outside FileBackend and FileOp.
316 * @param array $params
317 * @return Status
319 final public function nullInternal( array $params ) {
320 return Status::newGood();
323 final public function concatenate( array $params ) {
324 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
325 $status = Status::newGood();
327 // Try to lock the source files for the scope of this function
328 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager::LOCK_UW, $status );
329 if ( $status->isOK() ) {
330 // Actually do the file concatenation...
331 $start_time = microtime( true );
332 $status->merge( $this->doConcatenate( $params ) );
333 $sec = microtime( true ) - $start_time;
334 if ( !$status->isOK() ) {
335 wfDebugLog( 'FileOperation', get_class( $this ) . " failed to concatenate " .
336 count( $params['srcs'] ) . " file(s) [$sec sec]" );
340 return $status;
344 * @see FileBackendStore::concatenate()
345 * @return Status
347 protected function doConcatenate( array $params ) {
348 $status = Status::newGood();
349 $tmpPath = $params['dst']; // convenience
350 unset( $params['latest'] ); // sanity
352 // Check that the specified temp file is valid...
353 wfSuppressWarnings();
354 $ok = ( is_file( $tmpPath ) && filesize( $tmpPath ) == 0 );
355 wfRestoreWarnings();
356 if ( !$ok ) { // not present or not empty
357 $status->fatal( 'backend-fail-opentemp', $tmpPath );
358 return $status;
361 // Get local FS versions of the chunks needed for the concatenation...
362 $fsFiles = $this->getLocalReferenceMulti( $params );
363 foreach ( $fsFiles as $path => &$fsFile ) {
364 if ( !$fsFile ) { // chunk failed to download?
365 $fsFile = $this->getLocalReference( array( 'src' => $path ) );
366 if ( !$fsFile ) { // retry failed?
367 $status->fatal( 'backend-fail-read', $path );
368 return $status;
372 unset( $fsFile ); // unset reference so we can reuse $fsFile
374 // Get a handle for the destination temp file
375 $tmpHandle = fopen( $tmpPath, 'ab' );
376 if ( $tmpHandle === false ) {
377 $status->fatal( 'backend-fail-opentemp', $tmpPath );
378 return $status;
381 // Build up the temp file using the source chunks (in order)...
382 foreach ( $fsFiles as $virtualSource => $fsFile ) {
383 // Get a handle to the local FS version
384 $sourceHandle = fopen( $fsFile->getPath(), 'rb' );
385 if ( $sourceHandle === false ) {
386 fclose( $tmpHandle );
387 $status->fatal( 'backend-fail-read', $virtualSource );
388 return $status;
390 // Append chunk to file (pass chunk size to avoid magic quotes)
391 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
392 fclose( $sourceHandle );
393 fclose( $tmpHandle );
394 $status->fatal( 'backend-fail-writetemp', $tmpPath );
395 return $status;
397 fclose( $sourceHandle );
399 if ( !fclose( $tmpHandle ) ) {
400 $status->fatal( 'backend-fail-closetemp', $tmpPath );
401 return $status;
404 clearstatcache(); // temp file changed
406 return $status;
409 final protected function doPrepare( array $params ) {
410 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
411 $status = Status::newGood();
413 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
414 if ( $dir === null ) {
415 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
416 return $status; // invalid storage path
419 if ( $shard !== null ) { // confined to a single container/shard
420 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
421 } else { // directory is on several shards
422 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
423 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
424 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
425 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
429 return $status;
433 * @see FileBackendStore::doPrepare()
434 * @return Status
436 protected function doPrepareInternal( $container, $dir, array $params ) {
437 return Status::newGood();
440 final protected function doSecure( array $params ) {
441 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
442 $status = Status::newGood();
444 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
445 if ( $dir === null ) {
446 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
447 return $status; // invalid storage path
450 if ( $shard !== null ) { // confined to a single container/shard
451 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
452 } else { // directory is on several shards
453 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
454 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
455 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
456 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
460 return $status;
464 * @see FileBackendStore::doSecure()
465 * @return Status
467 protected function doSecureInternal( $container, $dir, array $params ) {
468 return Status::newGood();
471 final protected function doPublish( array $params ) {
472 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
473 $status = Status::newGood();
475 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
476 if ( $dir === null ) {
477 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
478 return $status; // invalid storage path
481 if ( $shard !== null ) { // confined to a single container/shard
482 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
483 } else { // directory is on several shards
484 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
485 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
486 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
487 $status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
491 return $status;
495 * @see FileBackendStore::doPublish()
496 * @return Status
498 protected function doPublishInternal( $container, $dir, array $params ) {
499 return Status::newGood();
502 final protected function doClean( array $params ) {
503 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
504 $status = Status::newGood();
506 // Recursive: first delete all empty subdirs recursively
507 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
508 $subDirsRel = $this->getTopDirectoryList( array( 'dir' => $params['dir'] ) );
509 if ( $subDirsRel !== null ) { // no errors
510 foreach ( $subDirsRel as $subDirRel ) {
511 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
512 $status->merge( $this->doClean( array( 'dir' => $subDir ) + $params ) );
514 unset( $subDirsRel ); // free directory for rmdir() on Windows (for FS backends)
518 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
519 if ( $dir === null ) {
520 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
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 return $status; // abort
531 if ( $shard !== null ) { // confined to a single container/shard
532 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
533 $this->deleteContainerCache( $fullCont ); // purge cache
534 } else { // directory is on several shards
535 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
536 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
537 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
538 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
539 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
543 return $status;
547 * @see FileBackendStore::doClean()
548 * @return Status
550 protected function doCleanInternal( $container, $dir, array $params ) {
551 return Status::newGood();
554 final public function fileExists( array $params ) {
555 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
556 $stat = $this->getFileStat( $params );
557 return ( $stat === null ) ? null : (bool)$stat; // null => failure
560 final public function getFileTimestamp( array $params ) {
561 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
562 $stat = $this->getFileStat( $params );
563 return $stat ? $stat['mtime'] : false;
566 final public function getFileSize( array $params ) {
567 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
568 $stat = $this->getFileStat( $params );
569 return $stat ? $stat['size'] : false;
572 final public function getFileStat( array $params ) {
573 $path = self::normalizeStoragePath( $params['src'] );
574 if ( $path === null ) {
575 return false; // invalid storage path
577 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
578 $latest = !empty( $params['latest'] ); // use latest data?
579 if ( !$this->cheapCache->has( $path, 'stat', self::CACHE_TTL ) ) {
580 $this->primeFileCache( array( $path ) ); // check persistent cache
582 if ( $this->cheapCache->has( $path, 'stat', self::CACHE_TTL ) ) {
583 $stat = $this->cheapCache->get( $path, 'stat' );
584 // If we want the latest data, check that this cached
585 // value was in fact fetched with the latest available data.
586 if ( is_array( $stat ) ) {
587 if ( !$latest || $stat['latest'] ) {
588 return $stat;
590 } elseif ( in_array( $stat, array( 'NOT_EXIST', 'NOT_EXIST_LATEST' ) ) ) {
591 if ( !$latest || $stat === 'NOT_EXIST_LATEST' ) {
592 return false;
596 wfProfileIn( __METHOD__ . '-miss' );
597 wfProfileIn( __METHOD__ . '-miss-' . $this->name );
598 $stat = $this->doGetFileStat( $params );
599 wfProfileOut( __METHOD__ . '-miss-' . $this->name );
600 wfProfileOut( __METHOD__ . '-miss' );
601 if ( is_array( $stat ) ) { // file exists
602 $stat['latest'] = $latest;
603 $this->cheapCache->set( $path, 'stat', $stat );
604 $this->setFileCache( $path, $stat ); // update persistent cache
605 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
606 $this->cheapCache->set( $path, 'sha1',
607 array( 'hash' => $stat['sha1'], 'latest' => $latest ) );
609 } elseif ( $stat === false ) { // file does not exist
610 $this->cheapCache->set( $path, 'stat', $latest ? 'NOT_EXIST_LATEST' : 'NOT_EXIST' );
611 $this->cheapCache->set( $path, 'sha1', // the SHA-1 must be false too
612 array( 'hash' => false, 'latest' => $latest ) );
613 wfDebug( __METHOD__ . ": File $path does not exist.\n" );
614 } else { // an error occurred
615 wfDebug( __METHOD__ . ": Could not stat file $path.\n" );
617 return $stat;
621 * @see FileBackendStore::getFileStat()
623 abstract protected function doGetFileStat( array $params );
625 public function getFileContentsMulti( array $params ) {
626 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
628 $params = $this->setConcurrencyFlags( $params );
629 $contents = $this->doGetFileContentsMulti( $params );
631 return $contents;
635 * @see FileBackendStore::getFileContentsMulti()
636 * @return Array
638 protected function doGetFileContentsMulti( array $params ) {
639 $contents = array();
640 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
641 wfSuppressWarnings();
642 $contents[$path] = $fsFile ? file_get_contents( $fsFile->getPath() ) : false;
643 wfRestoreWarnings();
645 return $contents;
648 final public function getFileSha1Base36( array $params ) {
649 $path = self::normalizeStoragePath( $params['src'] );
650 if ( $path === null ) {
651 return false; // invalid storage path
653 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
654 $latest = !empty( $params['latest'] ); // use latest data?
655 if ( $this->cheapCache->has( $path, 'sha1', self::CACHE_TTL ) ) {
656 $stat = $this->cheapCache->get( $path, 'sha1' );
657 // If we want the latest data, check that this cached
658 // value was in fact fetched with the latest available data.
659 if ( !$latest || $stat['latest'] ) {
660 return $stat['hash'];
663 wfProfileIn( __METHOD__ . '-miss' );
664 wfProfileIn( __METHOD__ . '-miss-' . $this->name );
665 $hash = $this->doGetFileSha1Base36( $params );
666 wfProfileOut( __METHOD__ . '-miss-' . $this->name );
667 wfProfileOut( __METHOD__ . '-miss' );
668 $this->cheapCache->set( $path, 'sha1', array( 'hash' => $hash, 'latest' => $latest ) );
669 return $hash;
673 * @see FileBackendStore::getFileSha1Base36()
674 * @return bool|string
676 protected function doGetFileSha1Base36( array $params ) {
677 $fsFile = $this->getLocalReference( $params );
678 if ( !$fsFile ) {
679 return false;
680 } else {
681 return $fsFile->getSha1Base36();
685 final public function getFileProps( array $params ) {
686 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
687 $fsFile = $this->getLocalReference( $params );
688 $props = $fsFile ? $fsFile->getProps() : FSFile::placeholderProps();
689 return $props;
692 final public function getLocalReferenceMulti( array $params ) {
693 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
695 $params = $this->setConcurrencyFlags( $params );
697 $fsFiles = array(); // (path => FSFile)
698 $latest = !empty( $params['latest'] ); // use latest data?
699 // Reuse any files already in process cache...
700 foreach ( $params['srcs'] as $src ) {
701 $path = self::normalizeStoragePath( $src );
702 if ( $path === null ) {
703 $fsFiles[$src] = null; // invalid storage path
704 } elseif ( $this->expensiveCache->has( $path, 'localRef' ) ) {
705 $val = $this->expensiveCache->get( $path, 'localRef' );
706 // If we want the latest data, check that this cached
707 // value was in fact fetched with the latest available data.
708 if ( !$latest || $val['latest'] ) {
709 $fsFiles[$src] = $val['object'];
713 // Fetch local references of any remaning files...
714 $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
715 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
716 $fsFiles[$path] = $fsFile;
717 if ( $fsFile ) { // update the process cache...
718 $this->expensiveCache->set( $path, 'localRef',
719 array( 'object' => $fsFile, 'latest' => $latest ) );
723 return $fsFiles;
727 * @see FileBackendStore::getLocalReferenceMulti()
728 * @return Array
730 protected function doGetLocalReferenceMulti( array $params ) {
731 return $this->doGetLocalCopyMulti( $params );
734 final public function getLocalCopyMulti( array $params ) {
735 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
737 $params = $this->setConcurrencyFlags( $params );
738 $tmpFiles = $this->doGetLocalCopyMulti( $params );
740 return $tmpFiles;
744 * @see FileBackendStore::getLocalCopyMulti()
745 * @return Array
747 abstract protected function doGetLocalCopyMulti( array $params );
750 * @see FileBackend::getFileHttpUrl()
751 * @return string|null
753 public function getFileHttpUrl( array $params ) {
754 return null; // not supported
757 final public function streamFile( array $params ) {
758 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
759 $status = Status::newGood();
761 $info = $this->getFileStat( $params );
762 if ( !$info ) { // let StreamFile handle the 404
763 $status->fatal( 'backend-fail-notexists', $params['src'] );
766 // Set output buffer and HTTP headers for stream
767 $extraHeaders = isset( $params['headers'] ) ? $params['headers'] : array();
768 $res = StreamFile::prepareForStream( $params['src'], $info, $extraHeaders );
769 if ( $res == StreamFile::NOT_MODIFIED ) {
770 // do nothing; client cache is up to date
771 } elseif ( $res == StreamFile::READY_STREAM ) {
772 wfProfileIn( __METHOD__ . '-send' );
773 wfProfileIn( __METHOD__ . '-send-' . $this->name );
774 $status = $this->doStreamFile( $params );
775 wfProfileOut( __METHOD__ . '-send-' . $this->name );
776 wfProfileOut( __METHOD__ . '-send' );
777 if ( !$status->isOK() ) {
778 // Per bug 41113, nasty things can happen if bad cache entries get
779 // stuck in cache. It's also possible that this error can come up
780 // with simple race conditions. Clear out the stat cache to be safe.
781 $this->clearCache( array( $params['src'] ) );
782 $this->deleteFileCache( $params['src'] );
783 trigger_error( "Bad stat cache or race condition for file {$params['src']}." );
785 } else {
786 $status->fatal( 'backend-fail-stream', $params['src'] );
789 return $status;
793 * @see FileBackendStore::streamFile()
794 * @return Status
796 protected function doStreamFile( array $params ) {
797 $status = Status::newGood();
799 $fsFile = $this->getLocalReference( $params );
800 if ( !$fsFile ) {
801 $status->fatal( 'backend-fail-stream', $params['src'] );
802 } elseif ( !readfile( $fsFile->getPath() ) ) {
803 $status->fatal( 'backend-fail-stream', $params['src'] );
806 return $status;
809 final public function directoryExists( array $params ) {
810 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
811 if ( $dir === null ) {
812 return false; // invalid storage path
814 if ( $shard !== null ) { // confined to a single container/shard
815 return $this->doDirectoryExists( $fullCont, $dir, $params );
816 } else { // directory is on several shards
817 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
818 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
819 $res = false; // response
820 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
821 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
822 if ( $exists ) {
823 $res = true;
824 break; // found one!
825 } elseif ( $exists === null ) { // error?
826 $res = null; // if we don't find anything, it is indeterminate
829 return $res;
834 * @see FileBackendStore::directoryExists()
836 * @param string $container Resolved container name
837 * @param string $dir Resolved path relative to container
838 * @param array $params
839 * @return bool|null
841 abstract protected function doDirectoryExists( $container, $dir, array $params );
843 final public function getDirectoryList( array $params ) {
844 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
845 if ( $dir === null ) { // invalid storage path
846 return null;
848 if ( $shard !== null ) {
849 // File listing is confined to a single container/shard
850 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
851 } else {
852 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
853 // File listing spans multiple containers/shards
854 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
855 return new FileBackendStoreShardDirIterator( $this,
856 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
861 * Do not call this function from places outside FileBackend
863 * @see FileBackendStore::getDirectoryList()
865 * @param string $container Resolved container name
866 * @param string $dir Resolved path relative to container
867 * @param array $params
868 * @return Traversable|Array|null Returns null on failure
870 abstract public function getDirectoryListInternal( $container, $dir, array $params );
872 final public function getFileList( array $params ) {
873 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
874 if ( $dir === null ) { // invalid storage path
875 return null;
877 if ( $shard !== null ) {
878 // File listing is confined to a single container/shard
879 return $this->getFileListInternal( $fullCont, $dir, $params );
880 } else {
881 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
882 // File listing spans multiple containers/shards
883 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
884 return new FileBackendStoreShardFileIterator( $this,
885 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
890 * Do not call this function from places outside FileBackend
892 * @see FileBackendStore::getFileList()
894 * @param string $container Resolved container name
895 * @param string $dir Resolved path relative to container
896 * @param array $params
897 * @return Traversable|Array|null Returns null on failure
899 abstract public function getFileListInternal( $container, $dir, array $params );
902 * Return a list of FileOp objects from a list of operations.
903 * Do not call this function from places outside FileBackend.
905 * The result must have the same number of items as the input.
906 * An exception is thrown if an unsupported operation is requested.
908 * @param array $ops Same format as doOperations()
909 * @return Array List of FileOp objects
910 * @throws MWException
912 final public function getOperationsInternal( array $ops ) {
913 $supportedOps = array(
914 'store' => 'StoreFileOp',
915 'copy' => 'CopyFileOp',
916 'move' => 'MoveFileOp',
917 'delete' => 'DeleteFileOp',
918 'create' => 'CreateFileOp',
919 'describe' => 'DescribeFileOp',
920 'null' => 'NullFileOp'
923 $performOps = array(); // array of FileOp objects
924 // Build up ordered array of FileOps...
925 foreach ( $ops as $operation ) {
926 $opName = $operation['op'];
927 if ( isset( $supportedOps[$opName] ) ) {
928 $class = $supportedOps[$opName];
929 // Get params for this operation
930 $params = $operation;
931 // Append the FileOp class
932 $performOps[] = new $class( $this, $params );
933 } else {
934 throw new MWException( "Operation '$opName' is not supported." );
938 return $performOps;
942 * Get a list of storage paths to lock for a list of operations
943 * Returns an array with 'sh' (shared) and 'ex' (exclusive) keys,
944 * each corresponding to a list of storage paths to be locked.
945 * All returned paths are normalized.
947 * @param array $performOps List of FileOp objects
948 * @return Array ('sh' => list of paths, 'ex' => list of paths)
950 final public function getPathsToLockForOpsInternal( array $performOps ) {
951 // Build up a list of files to lock...
952 $paths = array( 'sh' => array(), 'ex' => array() );
953 foreach ( $performOps as $fileOp ) {
954 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
955 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
957 // Optimization: if doing an EX lock anyway, don't also set an SH one
958 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
959 // Get a shared lock on the parent directory of each path changed
960 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
962 return $paths;
965 public function getScopedLocksForOps( array $ops, Status $status ) {
966 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
967 return array(
968 $this->getScopedFileLocks( $paths['sh'], LockManager::LOCK_UW, $status ),
969 $this->getScopedFileLocks( $paths['ex'], LockManager::LOCK_EX, $status )
973 final protected function doOperationsInternal( array $ops, array $opts ) {
974 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
975 $status = Status::newGood();
977 // Fix up custom header name/value pairs...
978 $ops = array_map( array( $this, 'stripInvalidHeadersFromOp' ), $ops );
980 // Build up a list of FileOps...
981 $performOps = $this->getOperationsInternal( $ops );
983 // Acquire any locks as needed...
984 if ( empty( $opts['nonLocking'] ) ) {
985 // Build up a list of files to lock...
986 $paths = $this->getPathsToLockForOpsInternal( $performOps );
987 // Try to lock those files for the scope of this function...
988 $scopeLockS = $this->getScopedFileLocks( $paths['sh'], LockManager::LOCK_UW, $status );
989 $scopeLockE = $this->getScopedFileLocks( $paths['ex'], LockManager::LOCK_EX, $status );
990 if ( !$status->isOK() ) {
991 return $status; // abort
995 // Clear any file cache entries (after locks acquired)
996 if ( empty( $opts['preserveCache'] ) ) {
997 $this->clearCache();
1000 // Load from the persistent file and container caches
1001 $this->primeFileCache( $performOps );
1002 $this->primeContainerCache( $performOps );
1004 // Actually attempt the operation batch...
1005 $opts = $this->setConcurrencyFlags( $opts );
1006 $subStatus = FileOpBatch::attempt( $performOps, $opts, $this->fileJournal );
1008 // Merge errors into status fields
1009 $status->merge( $subStatus );
1010 $status->success = $subStatus->success; // not done in merge()
1012 return $status;
1015 final protected function doQuickOperationsInternal( array $ops ) {
1016 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
1017 $status = Status::newGood();
1019 // Fix up custom header name/value pairs...
1020 $ops = array_map( array( $this, 'stripInvalidHeadersFromOp' ), $ops );
1022 // Clear any file cache entries
1023 $this->clearCache();
1025 $supportedOps = array( 'create', 'store', 'copy', 'move', 'delete', 'null' );
1026 $async = ( $this->parallelize === 'implicit' && count( $ops ) > 1 );
1027 $maxConcurrency = $this->concurrency; // throttle
1029 $statuses = array(); // array of (index => Status)
1030 $fileOpHandles = array(); // list of (index => handle) arrays
1031 $curFileOpHandles = array(); // current handle batch
1032 // Perform the sync-only ops and build up op handles for the async ops...
1033 foreach ( $ops as $index => $params ) {
1034 if ( !in_array( $params['op'], $supportedOps ) ) {
1035 throw new MWException( "Operation '{$params['op']}' is not supported." );
1037 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1038 $subStatus = $this->$method( array( 'async' => $async ) + $params );
1039 if ( $subStatus->value instanceof FileBackendStoreOpHandle ) { // async
1040 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1041 $fileOpHandles[] = $curFileOpHandles; // push this batch
1042 $curFileOpHandles = array();
1044 $curFileOpHandles[$index] = $subStatus->value; // keep index
1045 } else { // error or completed
1046 $statuses[$index] = $subStatus; // keep index
1049 if ( count( $curFileOpHandles ) ) {
1050 $fileOpHandles[] = $curFileOpHandles; // last batch
1052 // Do all the async ops that can be done concurrently...
1053 foreach ( $fileOpHandles as $fileHandleBatch ) {
1054 $statuses = $statuses + $this->executeOpHandlesInternal( $fileHandleBatch );
1056 // Marshall and merge all the responses...
1057 foreach ( $statuses as $index => $subStatus ) {
1058 $status->merge( $subStatus );
1059 if ( $subStatus->isOK() ) {
1060 $status->success[$index] = true;
1061 ++$status->successCount;
1062 } else {
1063 $status->success[$index] = false;
1064 ++$status->failCount;
1068 return $status;
1072 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1073 * The resulting Status object fields will correspond
1074 * to the order in which the handles where given.
1076 * @param array $handles List of FileBackendStoreOpHandle objects
1077 * @return Array Map of Status objects
1078 * @throws MWException
1080 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1081 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
1082 foreach ( $fileOpHandles as $fileOpHandle ) {
1083 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle ) ) {
1084 throw new MWException( "Given a non-FileBackendStoreOpHandle object." );
1085 } elseif ( $fileOpHandle->backend->getName() !== $this->getName() ) {
1086 throw new MWException( "Given a FileBackendStoreOpHandle for the wrong backend." );
1089 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1090 foreach ( $fileOpHandles as $fileOpHandle ) {
1091 $fileOpHandle->closeResources();
1093 return $res;
1097 * @see FileBackendStore::executeOpHandlesInternal()
1098 * @param array $fileOpHandles
1099 * @throws MWException
1100 * @return Array List of corresponding Status objects
1102 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1103 foreach ( $fileOpHandles as $fileOpHandle ) { // OK if empty
1104 throw new MWException( "This backend supports no asynchronous operations." );
1106 return array();
1110 * Strip long HTTP headers from a file operation.
1111 * Most headers are just numbers, but some are allowed to be long.
1112 * This function is useful for cleaning up headers and avoiding backend
1113 * specific errors, especially in the middle of batch file operations.
1115 * @param array $op Same format as doOperation()
1116 * @return Array
1118 protected function stripInvalidHeadersFromOp( array $op ) {
1119 static $longs = array( 'Content-Disposition' );
1120 if ( isset( $op['headers'] ) ) { // op sets HTTP headers
1121 foreach ( $op['headers'] as $name => $value ) {
1122 $maxHVLen = in_array( $name, $longs ) ? INF : 255;
1123 if ( strlen( $name ) > 255 || strlen( $value ) > $maxHVLen ) {
1124 trigger_error( "Header '$name: $value' is too long." );
1125 unset( $op['headers'][$name] );
1126 } elseif ( !strlen( $value ) ) {
1127 $op['headers'][$name] = ''; // null/false => ""
1131 return $op;
1134 final public function preloadCache( array $paths ) {
1135 $fullConts = array(); // full container names
1136 foreach ( $paths as $path ) {
1137 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1138 $fullConts[] = $fullCont;
1140 // Load from the persistent file and container caches
1141 $this->primeContainerCache( $fullConts );
1142 $this->primeFileCache( $paths );
1145 final public function clearCache( array $paths = null ) {
1146 if ( is_array( $paths ) ) {
1147 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1148 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1150 if ( $paths === null ) {
1151 $this->cheapCache->clear();
1152 $this->expensiveCache->clear();
1153 } else {
1154 foreach ( $paths as $path ) {
1155 $this->cheapCache->clear( $path );
1156 $this->expensiveCache->clear( $path );
1159 $this->doClearCache( $paths );
1163 * Clears any additional stat caches for storage paths
1165 * @see FileBackend::clearCache()
1167 * @param array $paths Storage paths (optional)
1168 * @return void
1170 protected function doClearCache( array $paths = null ) {}
1173 * Is this a key/value store where directories are just virtual?
1174 * Virtual directories exists in so much as files exists that are
1175 * prefixed with the directory path followed by a forward slash.
1177 * @return bool
1179 abstract protected function directoriesAreVirtual();
1182 * Check if a container name is valid.
1183 * This checks for for length and illegal characters.
1185 * @param string $container
1186 * @return bool
1188 final protected static function isValidContainerName( $container ) {
1189 // This accounts for Swift and S3 restrictions while leaving room
1190 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1191 // This disallows directory separators or traversal characters.
1192 // Note that matching strings URL encode to the same string;
1193 // in Swift, the length restriction is *after* URL encoding.
1194 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1198 * Splits a storage path into an internal container name,
1199 * an internal relative file name, and a container shard suffix.
1200 * Any shard suffix is already appended to the internal container name.
1201 * This also checks that the storage path is valid and within this backend.
1203 * If the container is sharded but a suffix could not be determined,
1204 * this means that the path can only refer to a directory and can only
1205 * be scanned by looking in all the container shards.
1207 * @param string $storagePath
1208 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1210 final protected function resolveStoragePath( $storagePath ) {
1211 list( $backend, $container, $relPath ) = self::splitStoragePath( $storagePath );
1212 if ( $backend === $this->name ) { // must be for this backend
1213 $relPath = self::normalizeContainerPath( $relPath );
1214 if ( $relPath !== null ) {
1215 // Get shard for the normalized path if this container is sharded
1216 $cShard = $this->getContainerShard( $container, $relPath );
1217 // Validate and sanitize the relative path (backend-specific)
1218 $relPath = $this->resolveContainerPath( $container, $relPath );
1219 if ( $relPath !== null ) {
1220 // Prepend any wiki ID prefix to the container name
1221 $container = $this->fullContainerName( $container );
1222 if ( self::isValidContainerName( $container ) ) {
1223 // Validate and sanitize the container name (backend-specific)
1224 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1225 if ( $container !== null ) {
1226 return array( $container, $relPath, $cShard );
1232 return array( null, null, null );
1236 * Like resolveStoragePath() except null values are returned if
1237 * the container is sharded and the shard could not be determined
1238 * or if the path ends with '/'. The later case is illegal for FS
1239 * backends and can confuse listings for object store backends.
1241 * This function is used when resolving paths that must be valid
1242 * locations for files. Directory and listing functions should
1243 * generally just use resolveStoragePath() instead.
1245 * @see FileBackendStore::resolveStoragePath()
1247 * @param string $storagePath
1248 * @return Array (container, path) or (null, null) if invalid
1250 final protected function resolveStoragePathReal( $storagePath ) {
1251 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1252 if ( $cShard !== null && substr( $relPath, -1 ) !== '/' ) {
1253 return array( $container, $relPath );
1255 return array( null, null );
1259 * Get the container name shard suffix for a given path.
1260 * Any empty suffix means the container is not sharded.
1262 * @param string $container Container name
1263 * @param string $relPath Storage path relative to the container
1264 * @return string|null Returns null if shard could not be determined
1266 final protected function getContainerShard( $container, $relPath ) {
1267 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1268 if ( $levels == 1 || $levels == 2 ) {
1269 // Hash characters are either base 16 or 36
1270 $char = ( $base == 36 ) ? '[0-9a-z]' : '[0-9a-f]';
1271 // Get a regex that represents the shard portion of paths.
1272 // The concatenation of the captures gives us the shard.
1273 if ( $levels === 1 ) { // 16 or 36 shards per container
1274 $hashDirRegex = '(' . $char . ')';
1275 } else { // 256 or 1296 shards per container
1276 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1277 $hashDirRegex = $char . '/(' . $char . '{2})';
1278 } else { // short hash dir format (e.g. "a/b/c")
1279 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1282 // Allow certain directories to be above the hash dirs so as
1283 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1284 // They must be 2+ chars to avoid any hash directory ambiguity.
1285 $m = array();
1286 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1287 return '.' . implode( '', array_slice( $m, 1 ) );
1289 return null; // failed to match
1291 return ''; // no sharding
1295 * Check if a storage path maps to a single shard.
1296 * Container dirs like "a", where the container shards on "x/xy",
1297 * can reside on several shards. Such paths are tricky to handle.
1299 * @param string $storagePath Storage path
1300 * @return bool
1302 final public function isSingleShardPathInternal( $storagePath ) {
1303 list( , , $shard ) = $this->resolveStoragePath( $storagePath );
1304 return ( $shard !== null );
1308 * Get the sharding config for a container.
1309 * If greater than 0, then all file storage paths within
1310 * the container are required to be hashed accordingly.
1312 * @param string $container
1313 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
1315 final protected function getContainerHashLevels( $container ) {
1316 if ( isset( $this->shardViaHashLevels[$container] ) ) {
1317 $config = $this->shardViaHashLevels[$container];
1318 $hashLevels = (int)$config['levels'];
1319 if ( $hashLevels == 1 || $hashLevels == 2 ) {
1320 $hashBase = (int)$config['base'];
1321 if ( $hashBase == 16 || $hashBase == 36 ) {
1322 return array( $hashLevels, $hashBase, $config['repeat'] );
1326 return array( 0, 0, false ); // no sharding
1330 * Get a list of full container shard suffixes for a container
1332 * @param string $container
1333 * @return Array
1335 final protected function getContainerSuffixes( $container ) {
1336 $shards = array();
1337 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1338 if ( $digits > 0 ) {
1339 $numShards = pow( $base, $digits );
1340 for ( $index = 0; $index < $numShards; $index++ ) {
1341 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1344 return $shards;
1348 * Get the full container name, including the wiki ID prefix
1350 * @param string $container
1351 * @return string
1353 final protected function fullContainerName( $container ) {
1354 if ( $this->wikiId != '' ) {
1355 return "{$this->wikiId}-$container";
1356 } else {
1357 return $container;
1362 * Resolve a container name, checking if it's allowed by the backend.
1363 * This is intended for internal use, such as encoding illegal chars.
1364 * Subclasses can override this to be more restrictive.
1366 * @param string $container
1367 * @return string|null
1369 protected function resolveContainerName( $container ) {
1370 return $container;
1374 * Resolve a relative storage path, checking if it's allowed by the backend.
1375 * This is intended for internal use, such as encoding illegal chars or perhaps
1376 * getting absolute paths (e.g. FS based backends). Note that the relative path
1377 * may be the empty string (e.g. the path is simply to the container).
1379 * @param string $container Container name
1380 * @param string $relStoragePath Storage path relative to the container
1381 * @return string|null Path or null if not valid
1383 protected function resolveContainerPath( $container, $relStoragePath ) {
1384 return $relStoragePath;
1388 * Get the cache key for a container
1390 * @param string $container Resolved container name
1391 * @return string
1393 private function containerCacheKey( $container ) {
1394 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1398 * Set the cached info for a container
1400 * @param string $container Resolved container name
1401 * @param array $val Information to cache
1402 * @return void
1404 final protected function setContainerCache( $container, array $val ) {
1405 $this->memCache->add( $this->containerCacheKey( $container ), $val, 14 * 86400 );
1409 * Delete the cached info for a container.
1410 * The cache key is salted for a while to prevent race conditions.
1412 * @param string $container Resolved container name
1413 * @return void
1415 final protected function deleteContainerCache( $container ) {
1416 if ( !$this->memCache->set( $this->containerCacheKey( $container ), 'PURGED', 300 ) ) {
1417 trigger_error( "Unable to delete stat cache for container $container." );
1422 * Do a batch lookup from cache for container stats for all containers
1423 * used in a list of container names, storage paths, or FileOp objects.
1424 * This loads the persistent cache values into the process cache.
1426 * @param Array $items
1427 * @return void
1429 final protected function primeContainerCache( array $items ) {
1430 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
1432 $paths = array(); // list of storage paths
1433 $contNames = array(); // (cache key => resolved container name)
1434 // Get all the paths/containers from the items...
1435 foreach ( $items as $item ) {
1436 if ( $item instanceof FileOp ) {
1437 $paths = array_merge( $paths, $item->storagePathsRead() );
1438 $paths = array_merge( $paths, $item->storagePathsChanged() );
1439 } elseif ( self::isStoragePath( $item ) ) {
1440 $paths[] = $item;
1441 } elseif ( is_string( $item ) ) { // full container name
1442 $contNames[$this->containerCacheKey( $item )] = $item;
1445 // Get all the corresponding cache keys for paths...
1446 foreach ( $paths as $path ) {
1447 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1448 if ( $fullCont !== null ) { // valid path for this backend
1449 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1453 $contInfo = array(); // (resolved container name => cache value)
1454 // Get all cache entries for these container cache keys...
1455 $values = $this->memCache->getMulti( array_keys( $contNames ) );
1456 foreach ( $values as $cacheKey => $val ) {
1457 $contInfo[$contNames[$cacheKey]] = $val;
1460 // Populate the container process cache for the backend...
1461 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1465 * Fill the backend-specific process cache given an array of
1466 * resolved container names and their corresponding cached info.
1467 * Only containers that actually exist should appear in the map.
1469 * @param array $containerInfo Map of resolved container names to cached info
1470 * @return void
1472 protected function doPrimeContainerCache( array $containerInfo ) {}
1475 * Get the cache key for a file path
1477 * @param string $path Normalized storage path
1478 * @return string
1480 private function fileCacheKey( $path ) {
1481 return wfMemcKey( 'backend', $this->getName(), 'file', sha1( $path ) );
1485 * Set the cached stat info for a file path.
1486 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1487 * salting for the case when a file is created at a path were there was none before.
1489 * @param string $path Storage path
1490 * @param array $val Stat information to cache
1491 * @return void
1493 final protected function setFileCache( $path, array $val ) {
1494 $path = FileBackend::normalizeStoragePath( $path );
1495 if ( $path === null ) {
1496 return; // invalid storage path
1498 $age = time() - wfTimestamp( TS_UNIX, $val['mtime'] );
1499 $ttl = min( 7 * 86400, max( 300, floor( .1 * $age ) ) );
1500 $this->memCache->add( $this->fileCacheKey( $path ), $val, $ttl );
1504 * Delete the cached stat info for a file path.
1505 * The cache key is salted for a while to prevent race conditions.
1506 * Since negatives (404s) are not cached, this does not need to be called when
1507 * a file is created at a path were there was none before.
1509 * @param string $path Storage path
1510 * @return void
1512 final protected function deleteFileCache( $path ) {
1513 $path = FileBackend::normalizeStoragePath( $path );
1514 if ( $path === null ) {
1515 return; // invalid storage path
1517 if ( !$this->memCache->set( $this->fileCacheKey( $path ), 'PURGED', 300 ) ) {
1518 trigger_error( "Unable to delete stat cache for file $path." );
1523 * Do a batch lookup from cache for file stats for all paths
1524 * used in a list of storage paths or FileOp objects.
1525 * This loads the persistent cache values into the process cache.
1527 * @param array $items List of storage paths or FileOps
1528 * @return void
1530 final protected function primeFileCache( array $items ) {
1531 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
1533 $paths = array(); // list of storage paths
1534 $pathNames = array(); // (cache key => storage path)
1535 // Get all the paths/containers from the items...
1536 foreach ( $items as $item ) {
1537 if ( $item instanceof FileOp ) {
1538 $paths = array_merge( $paths, $item->storagePathsRead() );
1539 $paths = array_merge( $paths, $item->storagePathsChanged() );
1540 } elseif ( self::isStoragePath( $item ) ) {
1541 $paths[] = FileBackend::normalizeStoragePath( $item );
1544 // Get rid of any paths that failed normalization...
1545 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1546 // Get all the corresponding cache keys for paths...
1547 foreach ( $paths as $path ) {
1548 list( , $rel, ) = $this->resolveStoragePath( $path );
1549 if ( $rel !== null ) { // valid path for this backend
1550 $pathNames[$this->fileCacheKey( $path )] = $path;
1553 // Get all cache entries for these container cache keys...
1554 $values = $this->memCache->getMulti( array_keys( $pathNames ) );
1555 foreach ( $values as $cacheKey => $val ) {
1556 if ( is_array( $val ) ) {
1557 $path = $pathNames[$cacheKey];
1558 $this->cheapCache->set( $path, 'stat', $val );
1559 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1560 $this->cheapCache->set( $path, 'sha1',
1561 array( 'hash' => $val['sha1'], 'latest' => $val['latest'] ) );
1568 * Set the 'concurrency' option from a list of operation options
1570 * @param array $opts Map of operation options
1571 * @return Array
1573 final protected function setConcurrencyFlags( array $opts ) {
1574 $opts['concurrency'] = 1; // off
1575 if ( $this->parallelize === 'implicit' ) {
1576 if ( !isset( $opts['parallelize'] ) || $opts['parallelize'] ) {
1577 $opts['concurrency'] = $this->concurrency;
1579 } elseif ( $this->parallelize === 'explicit' ) {
1580 if ( !empty( $opts['parallelize'] ) ) {
1581 $opts['concurrency'] = $this->concurrency;
1584 return $opts;
1589 * FileBackendStore helper class for performing asynchronous file operations.
1591 * For example, calling FileBackendStore::createInternal() with the "async"
1592 * param flag may result in a Status that contains this object as a value.
1593 * This class is largely backend-specific and is mostly just "magic" to be
1594 * passed to FileBackendStore::executeOpHandlesInternal().
1596 abstract class FileBackendStoreOpHandle {
1597 /** @var Array */
1598 public $params = array(); // params to caller functions
1599 /** @var FileBackendStore */
1600 public $backend;
1601 /** @var Array */
1602 public $resourcesToClose = array();
1604 public $call; // string; name that identifies the function called
1607 * Close all open file handles
1609 * @return void
1611 public function closeResources() {
1612 array_map( 'fclose', $this->resourcesToClose );
1617 * FileBackendStore helper function to handle listings that span container shards.
1618 * Do not use this class from places outside of FileBackendStore.
1620 * @ingroup FileBackend
1622 abstract class FileBackendStoreShardListIterator extends FilterIterator {
1623 /** @var FileBackendStore */
1624 protected $backend;
1625 /** @var Array */
1626 protected $params;
1628 protected $container; // string; full container name
1629 protected $directory; // string; resolved relative path
1631 /** @var Array */
1632 protected $multiShardPaths = array(); // (rel path => 1)
1635 * @param FileBackendStore $backend
1636 * @param string $container Full storage container name
1637 * @param string $dir Storage directory relative to container
1638 * @param array $suffixes List of container shard suffixes
1639 * @param array $params
1641 public function __construct(
1642 FileBackendStore $backend, $container, $dir, array $suffixes, array $params
1644 $this->backend = $backend;
1645 $this->container = $container;
1646 $this->directory = $dir;
1647 $this->params = $params;
1649 $iter = new AppendIterator();
1650 foreach ( $suffixes as $suffix ) {
1651 $iter->append( $this->listFromShard( $this->container . $suffix ) );
1654 parent::__construct( $iter );
1657 public function accept() {
1658 $rel = $this->getInnerIterator()->current(); // path relative to given directory
1659 $path = $this->params['dir'] . "/{$rel}"; // full storage path
1660 if ( $this->backend->isSingleShardPathInternal( $path ) ) {
1661 return true; // path is only on one shard; no issue with duplicates
1662 } elseif ( isset( $this->multiShardPaths[$rel] ) ) {
1663 // Don't keep listing paths that are on multiple shards
1664 return false;
1665 } else {
1666 $this->multiShardPaths[$rel] = 1;
1667 return true;
1671 public function rewind() {
1672 parent::rewind();
1673 $this->multiShardPaths = array();
1677 * Get the list for a given container shard
1679 * @param string $container Resolved container name
1680 * @return Iterator
1682 abstract protected function listFromShard( $container );
1686 * Iterator for listing directories
1688 class FileBackendStoreShardDirIterator extends FileBackendStoreShardListIterator {
1689 protected function listFromShard( $container ) {
1690 $list = $this->backend->getDirectoryListInternal(
1691 $container, $this->directory, $this->params );
1692 if ( $list === null ) {
1693 return new ArrayIterator( array() );
1694 } else {
1695 return is_array( $list ) ? new ArrayIterator( $list ) : $list;
1701 * Iterator for listing regular files
1703 class FileBackendStoreShardFileIterator extends FileBackendStoreShardListIterator {
1704 protected function listFromShard( $container ) {
1705 $list = $this->backend->getFileListInternal(
1706 $container, $this->directory, $this->params );
1707 if ( $list === null ) {
1708 return new ArrayIterator( array() );
1709 } else {
1710 return is_array( $list ) ? new ArrayIterator( $list ) : $list;