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
{
42 /** @var Array Map of paths to small (RAM/disk) cache items */
43 protected $cache = array(); // (storage path => key => value)
44 protected $maxCacheSize = 300; // integer; max paths with entries
45 /** @var Array Map of paths to large (RAM/disk) cache items */
46 protected $expensiveCache = array(); // (storage path => key => value)
47 protected $maxExpensiveCacheSize = 5; // integer; max paths with entries
49 /** @var Array Map of container names to sharding settings */
50 protected $shardViaHashLevels = array(); // (container name => config array)
52 protected $maxFileSize = 4294967296; // integer bytes (4GiB)
55 * @see FileBackend::__construct()
57 * @param $config Array
59 public function __construct( array $config ) {
60 parent
::__construct( $config );
61 $this->memCache
= new EmptyBagOStuff(); // disabled by default
65 * Get the maximum allowable file size given backend
66 * medium restrictions and basic performance constraints.
67 * Do not call this function from places outside FileBackend and FileOp.
69 * @return integer Bytes
71 final public function maxFileSizeInternal() {
72 return $this->maxFileSize
;
76 * Check if a file can be created at a given storage path.
77 * FS backends should check if the parent directory exists and the file is writable.
78 * Backends using key/value stores should check if the container exists.
80 * @param $storagePath string
83 abstract public function isPathUsableInternal( $storagePath );
86 * Create a file in the backend with the given contents.
87 * Do not call this function from places outside FileBackend and FileOp.
90 * content : the raw file contents
91 * dst : destination storage path
92 * overwrite : overwrite any file that exists at the destination
93 * async : Status will be returned immediately if supported.
94 * If the status is OK, then its value field will be
95 * set to a FileBackendStoreOpHandle object.
97 * @param $params Array
100 final public function createInternal( array $params ) {
101 wfProfileIn( __METHOD__
);
102 wfProfileIn( __METHOD__
. '-' . $this->name
);
103 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
104 $status = Status
::newFatal( 'backend-fail-maxsize',
105 $params['dst'], $this->maxFileSizeInternal() );
107 $status = $this->doCreateInternal( $params );
108 $this->clearCache( array( $params['dst'] ) );
109 $this->deleteFileCache( $params['dst'] ); // persistent cache
111 wfProfileOut( __METHOD__
. '-' . $this->name
);
112 wfProfileOut( __METHOD__
);
117 * @see FileBackendStore::createInternal()
119 abstract protected function doCreateInternal( array $params );
122 * Store a file into the backend from a file on disk.
123 * Do not call this function from places outside FileBackend and FileOp.
126 * src : source path on disk
127 * dst : destination storage path
128 * overwrite : overwrite any file that exists at the destination
129 * async : Status will be returned immediately if supported.
130 * If the status is OK, then its value field will be
131 * set to a FileBackendStoreOpHandle object.
133 * @param $params Array
136 final public function storeInternal( array $params ) {
137 wfProfileIn( __METHOD__
);
138 wfProfileIn( __METHOD__
. '-' . $this->name
);
139 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
140 $status = Status
::newFatal( 'backend-fail-maxsize',
141 $params['dst'], $this->maxFileSizeInternal() );
143 $status = $this->doStoreInternal( $params );
144 $this->clearCache( array( $params['dst'] ) );
145 $this->deleteFileCache( $params['dst'] ); // persistent cache
147 wfProfileOut( __METHOD__
. '-' . $this->name
);
148 wfProfileOut( __METHOD__
);
153 * @see FileBackendStore::storeInternal()
155 abstract protected function doStoreInternal( array $params );
158 * Copy a file from one storage path to another in the backend.
159 * Do not call this function from places outside FileBackend and FileOp.
162 * src : source storage path
163 * dst : destination storage path
164 * overwrite : overwrite any file that exists at the destination
165 * async : Status will be returned immediately if supported.
166 * If the status is OK, then its value field will be
167 * set to a FileBackendStoreOpHandle object.
169 * @param $params Array
172 final public function copyInternal( array $params ) {
173 wfProfileIn( __METHOD__
);
174 wfProfileIn( __METHOD__
. '-' . $this->name
);
175 $status = $this->doCopyInternal( $params );
176 $this->clearCache( array( $params['dst'] ) );
177 $this->deleteFileCache( $params['dst'] ); // persistent cache
178 wfProfileOut( __METHOD__
. '-' . $this->name
);
179 wfProfileOut( __METHOD__
);
184 * @see FileBackendStore::copyInternal()
186 abstract protected function doCopyInternal( array $params );
189 * Delete a file at the storage path.
190 * Do not call this function from places outside FileBackend and FileOp.
193 * src : source storage path
194 * ignoreMissingSource : do nothing if the source file does not exist
195 * async : Status will be returned immediately if supported.
196 * If the status is OK, then its value field will be
197 * set to a FileBackendStoreOpHandle object.
199 * @param $params Array
202 final public function deleteInternal( array $params ) {
203 wfProfileIn( __METHOD__
);
204 wfProfileIn( __METHOD__
. '-' . $this->name
);
205 $status = $this->doDeleteInternal( $params );
206 $this->clearCache( array( $params['src'] ) );
207 $this->deleteFileCache( $params['src'] ); // persistent cache
208 wfProfileOut( __METHOD__
. '-' . $this->name
);
209 wfProfileOut( __METHOD__
);
214 * @see FileBackendStore::deleteInternal()
216 abstract protected function doDeleteInternal( array $params );
219 * Move a file from one storage path to another in the backend.
220 * Do not call this function from places outside FileBackend and FileOp.
223 * src : source storage path
224 * dst : destination storage path
225 * overwrite : overwrite any file that exists at the destination
226 * async : Status will be returned immediately if supported.
227 * If the status is OK, then its value field will be
228 * set to a FileBackendStoreOpHandle object.
230 * @param $params Array
233 final public function moveInternal( array $params ) {
234 wfProfileIn( __METHOD__
);
235 wfProfileIn( __METHOD__
. '-' . $this->name
);
236 $status = $this->doMoveInternal( $params );
237 $this->clearCache( array( $params['src'], $params['dst'] ) );
238 $this->deleteFileCache( $params['src'] ); // persistent cache
239 $this->deleteFileCache( $params['dst'] ); // persistent cache
240 wfProfileOut( __METHOD__
. '-' . $this->name
);
241 wfProfileOut( __METHOD__
);
246 * @see FileBackendStore::moveInternal()
249 protected function doMoveInternal( array $params ) {
250 unset( $params['async'] ); // two steps, won't work here :)
251 // Copy source to dest
252 $status = $this->copyInternal( $params );
253 if ( $status->isOK() ) {
254 // Delete source (only fails due to races or medium going down)
255 $status->merge( $this->deleteInternal( array( 'src' => $params['src'] ) ) );
256 $status->setResult( true, $status->value
); // ignore delete() errors
262 * No-op file operation that does nothing.
263 * Do not call this function from places outside FileBackend and FileOp.
265 * @param $params Array
268 final public function nullInternal( array $params ) {
269 return Status
::newGood();
273 * @see FileBackend::concatenate()
276 final public function concatenate( array $params ) {
277 wfProfileIn( __METHOD__
);
278 wfProfileIn( __METHOD__
. '-' . $this->name
);
279 $status = Status
::newGood();
281 // Try to lock the source files for the scope of this function
282 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager
::LOCK_UW
, $status );
283 if ( $status->isOK() ) {
284 // Actually do the concatenation
285 $status->merge( $this->doConcatenate( $params ) );
288 wfProfileOut( __METHOD__
. '-' . $this->name
);
289 wfProfileOut( __METHOD__
);
294 * @see FileBackendStore::concatenate()
297 protected function doConcatenate( array $params ) {
298 $status = Status
::newGood();
299 $tmpPath = $params['dst']; // convenience
301 // Check that the specified temp file is valid...
302 wfSuppressWarnings();
303 $ok = ( is_file( $tmpPath ) && !filesize( $tmpPath ) );
305 if ( !$ok ) { // not present or not empty
306 $status->fatal( 'backend-fail-opentemp', $tmpPath );
310 // Build up the temp file using the source chunks (in order)...
311 $tmpHandle = fopen( $tmpPath, 'ab' );
312 if ( $tmpHandle === false ) {
313 $status->fatal( 'backend-fail-opentemp', $tmpPath );
316 foreach ( $params['srcs'] as $virtualSource ) {
317 // Get a local FS version of the chunk
318 $tmpFile = $this->getLocalReference( array( 'src' => $virtualSource ) );
320 $status->fatal( 'backend-fail-read', $virtualSource );
323 // Get a handle to the local FS version
324 $sourceHandle = fopen( $tmpFile->getPath(), 'r' );
325 if ( $sourceHandle === false ) {
326 fclose( $tmpHandle );
327 $status->fatal( 'backend-fail-read', $virtualSource );
330 // Append chunk to file (pass chunk size to avoid magic quotes)
331 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
332 fclose( $sourceHandle );
333 fclose( $tmpHandle );
334 $status->fatal( 'backend-fail-writetemp', $tmpPath );
337 fclose( $sourceHandle );
339 if ( !fclose( $tmpHandle ) ) {
340 $status->fatal( 'backend-fail-closetemp', $tmpPath );
344 clearstatcache(); // temp file changed
350 * @see FileBackend::doPrepare()
353 final protected function doPrepare( array $params ) {
354 wfProfileIn( __METHOD__
);
355 wfProfileIn( __METHOD__
. '-' . $this->name
);
357 $status = Status
::newGood();
358 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
359 if ( $dir === null ) {
360 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
361 wfProfileOut( __METHOD__
. '-' . $this->name
);
362 wfProfileOut( __METHOD__
);
363 return $status; // invalid storage path
366 if ( $shard !== null ) { // confined to a single container/shard
367 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
368 } else { // directory is on several shards
369 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
370 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
371 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
372 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
376 wfProfileOut( __METHOD__
. '-' . $this->name
);
377 wfProfileOut( __METHOD__
);
382 * @see FileBackendStore::doPrepare()
385 protected function doPrepareInternal( $container, $dir, array $params ) {
386 return Status
::newGood();
390 * @see FileBackend::doSecure()
393 final protected function doSecure( array $params ) {
394 wfProfileIn( __METHOD__
);
395 wfProfileIn( __METHOD__
. '-' . $this->name
);
396 $status = Status
::newGood();
398 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
399 if ( $dir === null ) {
400 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
401 wfProfileOut( __METHOD__
. '-' . $this->name
);
402 wfProfileOut( __METHOD__
);
403 return $status; // invalid storage path
406 if ( $shard !== null ) { // confined to a single container/shard
407 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
408 } else { // directory is on several shards
409 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
410 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
411 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
412 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
416 wfProfileOut( __METHOD__
. '-' . $this->name
);
417 wfProfileOut( __METHOD__
);
422 * @see FileBackendStore::doSecure()
425 protected function doSecureInternal( $container, $dir, array $params ) {
426 return Status
::newGood();
430 * @see FileBackend::doClean()
433 final protected function doClean( array $params ) {
434 wfProfileIn( __METHOD__
);
435 wfProfileIn( __METHOD__
. '-' . $this->name
);
436 $status = Status
::newGood();
438 // Recursive: first delete all empty subdirs recursively
439 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
440 $subDirsRel = $this->getTopDirectoryList( array( 'dir' => $params['dir'] ) );
441 if ( $subDirsRel !== null ) { // no errors
442 foreach ( $subDirsRel as $subDirRel ) {
443 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
444 $status->merge( $this->doClean( array( 'dir' => $subDir ) +
$params ) );
449 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
450 if ( $dir === null ) {
451 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
452 wfProfileOut( __METHOD__
. '-' . $this->name
);
453 wfProfileOut( __METHOD__
);
454 return $status; // invalid storage path
457 // Attempt to lock this directory...
458 $filesLockEx = array( $params['dir'] );
459 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
460 if ( !$status->isOK() ) {
461 wfProfileOut( __METHOD__
. '-' . $this->name
);
462 wfProfileOut( __METHOD__
);
463 return $status; // abort
466 if ( $shard !== null ) { // confined to a single container/shard
467 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
468 $this->deleteContainerCache( $fullCont ); // purge cache
469 } else { // directory is on several shards
470 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
471 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
472 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
473 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
474 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
478 wfProfileOut( __METHOD__
. '-' . $this->name
);
479 wfProfileOut( __METHOD__
);
484 * @see FileBackendStore::doClean()
487 protected function doCleanInternal( $container, $dir, array $params ) {
488 return Status
::newGood();
492 * @see FileBackend::fileExists()
495 final public function fileExists( array $params ) {
496 wfProfileIn( __METHOD__
);
497 wfProfileIn( __METHOD__
. '-' . $this->name
);
498 $stat = $this->getFileStat( $params );
499 wfProfileOut( __METHOD__
. '-' . $this->name
);
500 wfProfileOut( __METHOD__
);
501 return ( $stat === null ) ?
null : (bool)$stat; // null => failure
505 * @see FileBackend::getFileTimestamp()
508 final public function getFileTimestamp( array $params ) {
509 wfProfileIn( __METHOD__
);
510 wfProfileIn( __METHOD__
. '-' . $this->name
);
511 $stat = $this->getFileStat( $params );
512 wfProfileOut( __METHOD__
. '-' . $this->name
);
513 wfProfileOut( __METHOD__
);
514 return $stat ?
$stat['mtime'] : false;
518 * @see FileBackend::getFileSize()
521 final public function getFileSize( array $params ) {
522 wfProfileIn( __METHOD__
);
523 wfProfileIn( __METHOD__
. '-' . $this->name
);
524 $stat = $this->getFileStat( $params );
525 wfProfileOut( __METHOD__
. '-' . $this->name
);
526 wfProfileOut( __METHOD__
);
527 return $stat ?
$stat['size'] : false;
531 * @see FileBackend::getFileStat()
534 final public function getFileStat( array $params ) {
535 wfProfileIn( __METHOD__
);
536 wfProfileIn( __METHOD__
. '-' . $this->name
);
537 $path = self
::normalizeStoragePath( $params['src'] );
538 if ( $path === null ) {
539 wfProfileOut( __METHOD__
. '-' . $this->name
);
540 wfProfileOut( __METHOD__
);
541 return false; // invalid storage path
543 $latest = !empty( $params['latest'] ); // use latest data?
544 if ( !isset( $this->cache
[$path]['stat'] ) ) {
545 $this->primeFileCache( array( $path ) ); // check persistent cache
547 if ( isset( $this->cache
[$path]['stat'] ) ) {
548 // If we want the latest data, check that this cached
549 // value was in fact fetched with the latest available data.
550 if ( !$latest ||
$this->cache
[$path]['stat']['latest'] ) {
551 $this->pingCache( $path ); // LRU
552 wfProfileOut( __METHOD__
. '-' . $this->name
);
553 wfProfileOut( __METHOD__
);
554 return $this->cache
[$path]['stat'];
557 wfProfileIn( __METHOD__
. '-miss' );
558 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
559 $stat = $this->doGetFileStat( $params );
560 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
561 wfProfileOut( __METHOD__
. '-miss' );
562 if ( is_array( $stat ) ) { // don't cache negatives
563 $stat['latest'] = $latest;
564 $this->trimCache(); // limit memory
565 $this->cache
[$path]['stat'] = $stat;
566 $this->setFileCache( $path, $stat ); // update persistent cache
568 wfProfileOut( __METHOD__
. '-' . $this->name
);
569 wfProfileOut( __METHOD__
);
574 * @see FileBackendStore::getFileStat()
576 abstract protected function doGetFileStat( array $params );
579 * @see FileBackend::getFileContents()
580 * @return bool|string
582 public function getFileContents( array $params ) {
583 wfProfileIn( __METHOD__
);
584 wfProfileIn( __METHOD__
. '-' . $this->name
);
585 $tmpFile = $this->getLocalReference( $params );
587 wfProfileOut( __METHOD__
. '-' . $this->name
);
588 wfProfileOut( __METHOD__
);
591 wfSuppressWarnings();
592 $data = file_get_contents( $tmpFile->getPath() );
594 wfProfileOut( __METHOD__
. '-' . $this->name
);
595 wfProfileOut( __METHOD__
);
600 * @see FileBackend::getFileSha1Base36()
601 * @return bool|string
603 final public function getFileSha1Base36( array $params ) {
604 wfProfileIn( __METHOD__
);
605 wfProfileIn( __METHOD__
. '-' . $this->name
);
606 $path = $params['src'];
607 if ( isset( $this->cache
[$path]['sha1'] ) ) {
608 $this->pingCache( $path ); // LRU
609 wfProfileOut( __METHOD__
. '-' . $this->name
);
610 wfProfileOut( __METHOD__
);
611 return $this->cache
[$path]['sha1'];
613 wfProfileIn( __METHOD__
. '-miss' );
614 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
615 $hash = $this->doGetFileSha1Base36( $params );
616 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
617 wfProfileOut( __METHOD__
. '-miss' );
618 if ( $hash ) { // don't cache negatives
619 $this->trimCache(); // limit memory
620 $this->cache
[$path]['sha1'] = $hash;
622 wfProfileOut( __METHOD__
. '-' . $this->name
);
623 wfProfileOut( __METHOD__
);
628 * @see FileBackendStore::getFileSha1Base36()
631 protected function doGetFileSha1Base36( array $params ) {
632 $fsFile = $this->getLocalReference( $params );
636 return $fsFile->getSha1Base36();
641 * @see FileBackend::getFileProps()
644 final public function getFileProps( array $params ) {
645 wfProfileIn( __METHOD__
);
646 wfProfileIn( __METHOD__
. '-' . $this->name
);
647 $fsFile = $this->getLocalReference( $params );
648 $props = $fsFile ?
$fsFile->getProps() : FSFile
::placeholderProps();
649 wfProfileOut( __METHOD__
. '-' . $this->name
);
650 wfProfileOut( __METHOD__
);
655 * @see FileBackend::getLocalReference()
656 * @return TempFSFile|null
658 public function getLocalReference( array $params ) {
659 wfProfileIn( __METHOD__
);
660 wfProfileIn( __METHOD__
. '-' . $this->name
);
661 $path = $params['src'];
662 if ( isset( $this->expensiveCache
[$path]['localRef'] ) ) {
663 $this->pingExpensiveCache( $path );
664 wfProfileOut( __METHOD__
. '-' . $this->name
);
665 wfProfileOut( __METHOD__
);
666 return $this->expensiveCache
[$path]['localRef'];
668 $tmpFile = $this->getLocalCopy( $params );
669 if ( $tmpFile ) { // don't cache negatives
670 $this->trimExpensiveCache(); // limit memory
671 $this->expensiveCache
[$path]['localRef'] = $tmpFile;
673 wfProfileOut( __METHOD__
. '-' . $this->name
);
674 wfProfileOut( __METHOD__
);
679 * @see FileBackend::streamFile()
682 final public function streamFile( array $params ) {
683 wfProfileIn( __METHOD__
);
684 wfProfileIn( __METHOD__
. '-' . $this->name
);
685 $status = Status
::newGood();
687 $info = $this->getFileStat( $params );
688 if ( !$info ) { // let StreamFile handle the 404
689 $status->fatal( 'backend-fail-notexists', $params['src'] );
692 // Set output buffer and HTTP headers for stream
693 $extraHeaders = isset( $params['headers'] ) ?
$params['headers'] : array();
694 $res = StreamFile
::prepareForStream( $params['src'], $info, $extraHeaders );
695 if ( $res == StreamFile
::NOT_MODIFIED
) {
696 // do nothing; client cache is up to date
697 } elseif ( $res == StreamFile
::READY_STREAM
) {
698 wfProfileIn( __METHOD__
. '-send' );
699 wfProfileIn( __METHOD__
. '-send-' . $this->name
);
700 $status = $this->doStreamFile( $params );
701 wfProfileOut( __METHOD__
. '-send-' . $this->name
);
702 wfProfileOut( __METHOD__
. '-send' );
704 $status->fatal( 'backend-fail-stream', $params['src'] );
707 wfProfileOut( __METHOD__
. '-' . $this->name
);
708 wfProfileOut( __METHOD__
);
713 * @see FileBackendStore::streamFile()
716 protected function doStreamFile( array $params ) {
717 $status = Status
::newGood();
719 $fsFile = $this->getLocalReference( $params );
721 $status->fatal( 'backend-fail-stream', $params['src'] );
722 } elseif ( !readfile( $fsFile->getPath() ) ) {
723 $status->fatal( 'backend-fail-stream', $params['src'] );
730 * @see FileBackend::directoryExists()
733 final public function directoryExists( array $params ) {
734 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
735 if ( $dir === null ) {
736 return false; // invalid storage path
738 if ( $shard !== null ) { // confined to a single container/shard
739 return $this->doDirectoryExists( $fullCont, $dir, $params );
740 } else { // directory is on several shards
741 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
742 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
743 $res = false; // response
744 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
745 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
749 } elseif ( $exists === null ) { // error?
750 $res = null; // if we don't find anything, it is indeterminate
758 * @see FileBackendStore::directoryExists()
760 * @param $container string Resolved container name
761 * @param $dir string Resolved path relative to container
762 * @param $params Array
765 abstract protected function doDirectoryExists( $container, $dir, array $params );
768 * @see FileBackend::getDirectoryList()
769 * @return Traversable|Array|null Returns null on failure
771 final public function getDirectoryList( array $params ) {
772 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
773 if ( $dir === null ) { // invalid storage path
776 if ( $shard !== null ) {
777 // File listing is confined to a single container/shard
778 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
780 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
781 // File listing spans multiple containers/shards
782 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
783 return new FileBackendStoreShardDirIterator( $this,
784 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
789 * Do not call this function from places outside FileBackend
791 * @see FileBackendStore::getDirectoryList()
793 * @param $container string Resolved container name
794 * @param $dir string Resolved path relative to container
795 * @param $params Array
796 * @return Traversable|Array|null Returns null on failure
798 abstract public function getDirectoryListInternal( $container, $dir, array $params );
801 * @see FileBackend::getFileList()
802 * @return Traversable|Array|null Returns null on failure
804 final public function getFileList( array $params ) {
805 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
806 if ( $dir === null ) { // invalid storage path
809 if ( $shard !== null ) {
810 // File listing is confined to a single container/shard
811 return $this->getFileListInternal( $fullCont, $dir, $params );
813 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
814 // File listing spans multiple containers/shards
815 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
816 return new FileBackendStoreShardFileIterator( $this,
817 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
822 * Do not call this function from places outside FileBackend
824 * @see FileBackendStore::getFileList()
826 * @param $container string Resolved container name
827 * @param $dir string Resolved path relative to container
828 * @param $params Array
829 * @return Traversable|Array|null Returns null on failure
831 abstract public function getFileListInternal( $container, $dir, array $params );
834 * Return a list of FileOp objects from a list of operations.
835 * Do not call this function from places outside FileBackend.
837 * The result must have the same number of items as the input.
838 * An exception is thrown if an unsupported operation is requested.
840 * @param $ops Array Same format as doOperations()
841 * @return Array List of FileOp objects
842 * @throws MWException
844 final public function getOperationsInternal( array $ops ) {
845 $supportedOps = array(
846 'store' => 'StoreFileOp',
847 'copy' => 'CopyFileOp',
848 'move' => 'MoveFileOp',
849 'delete' => 'DeleteFileOp',
850 'create' => 'CreateFileOp',
851 'null' => 'NullFileOp'
854 $performOps = array(); // array of FileOp objects
855 // Build up ordered array of FileOps...
856 foreach ( $ops as $operation ) {
857 $opName = $operation['op'];
858 if ( isset( $supportedOps[$opName] ) ) {
859 $class = $supportedOps[$opName];
860 // Get params for this operation
861 $params = $operation;
862 // Append the FileOp class
863 $performOps[] = new $class( $this, $params );
865 throw new MWException( "Operation '$opName' is not supported." );
873 * Get a list of storage paths to lock for a list of operations
874 * Returns an array with 'sh' (shared) and 'ex' (exclusive) keys,
875 * each corresponding to a list of storage paths to be locked.
877 * @param $performOps Array List of FileOp objects
878 * @return Array ('sh' => list of paths, 'ex' => list of paths)
880 final public function getPathsToLockForOpsInternal( array $performOps ) {
881 // Build up a list of files to lock...
882 $paths = array( 'sh' => array(), 'ex' => array() );
883 foreach ( $performOps as $fileOp ) {
884 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
885 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
887 // Optimization: if doing an EX lock anyway, don't also set an SH one
888 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
889 // Get a shared lock on the parent directory of each path changed
890 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
896 * @see FileBackend::doOperationsInternal()
899 protected function doOperationsInternal( array $ops, array $opts ) {
900 wfProfileIn( __METHOD__
);
901 wfProfileIn( __METHOD__
. '-' . $this->name
);
902 $status = Status
::newGood();
904 // Build up a list of FileOps...
905 $performOps = $this->getOperationsInternal( $ops );
907 // Acquire any locks as needed...
908 if ( empty( $opts['nonLocking'] ) ) {
909 // Build up a list of files to lock...
910 $paths = $this->getPathsToLockForOpsInternal( $performOps );
911 // Try to lock those files for the scope of this function...
912 $scopeLockS = $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status );
913 $scopeLockE = $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status );
914 if ( !$status->isOK() ) {
915 wfProfileOut( __METHOD__
. '-' . $this->name
);
916 wfProfileOut( __METHOD__
);
917 return $status; // abort
921 // Clear any file cache entries (after locks acquired)
924 // Load from the persistent file and container caches
925 $this->primeFileCache( $performOps );
926 $this->primeContainerCache( $performOps );
928 // Actually attempt the operation batch...
929 $subStatus = FileOpBatch
::attempt( $performOps, $opts, $this->fileJournal
);
931 // Merge errors into status fields
932 $status->merge( $subStatus );
933 $status->success
= $subStatus->success
; // not done in merge()
935 wfProfileOut( __METHOD__
. '-' . $this->name
);
936 wfProfileOut( __METHOD__
);
941 * @see FileBackend::doQuickOperationsInternal()
943 * @throws MWException
945 final protected function doQuickOperationsInternal( array $ops ) {
946 wfProfileIn( __METHOD__
);
947 wfProfileIn( __METHOD__
. '-' . $this->name
);
948 $status = Status
::newGood();
950 $async = $this->parallelize
;
951 $maxConcurrency = $this->concurrency
; // throttle
953 $statuses = array(); // array of (index => Status)
954 $fileOpHandles = array(); // list of (index => handle) arrays
955 $curFileOpHandles = array(); // current handle batch
956 // Perform the sync-only ops and build up op handles for the async ops...
957 foreach ( $ops as $index => $params ) {
958 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
959 if ( !MWInit
::methodExists( __CLASS__
, $method ) ) {
960 wfProfileOut( __METHOD__
. '-' . $this->name
);
961 wfProfileOut( __METHOD__
);
962 throw new MWException( "Operation '{$params['op']}' is not supported." );
964 $subStatus = $this->$method( array( 'async' => $async ) +
$params );
965 if ( $subStatus->value
instanceof FileBackendStoreOpHandle
) { // async
966 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
967 $fileOpHandles[] = $curFileOpHandles; // push this batch
968 $curFileOpHandles = array();
970 $curFileOpHandles[$index] = $subStatus->value
; // keep index
971 } else { // error or completed
972 $statuses[$index] = $subStatus; // keep index
975 if ( count( $curFileOpHandles ) ) {
976 $fileOpHandles[] = $curFileOpHandles; // last batch
978 // Do all the async ops that can be done concurrently...
979 foreach ( $fileOpHandles as $fileHandleBatch ) {
980 $statuses = $statuses +
$this->executeOpHandlesInternal( $fileHandleBatch );
982 // Marshall and merge all the responses...
983 foreach ( $statuses as $index => $subStatus ) {
984 $status->merge( $subStatus );
985 if ( $subStatus->isOK() ) {
986 $status->success
[$index] = true;
987 ++
$status->successCount
;
989 $status->success
[$index] = false;
990 ++
$status->failCount
;
994 wfProfileOut( __METHOD__
. '-' . $this->name
);
995 wfProfileOut( __METHOD__
);
1000 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1001 * The resulting Status object fields will correspond
1002 * to the order in which the handles where given.
1004 * @param $handles Array List of FileBackendStoreOpHandle objects
1005 * @return Array Map of Status objects
1006 * @throws MWException
1008 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1009 wfProfileIn( __METHOD__
);
1010 wfProfileIn( __METHOD__
. '-' . $this->name
);
1011 foreach ( $fileOpHandles as $fileOpHandle ) {
1012 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle
) ) {
1013 throw new MWException( "Given a non-FileBackendStoreOpHandle object." );
1014 } elseif ( $fileOpHandle->backend
->getName() !== $this->getName() ) {
1015 throw new MWException( "Given a FileBackendStoreOpHandle for the wrong backend." );
1018 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1019 wfProfileOut( __METHOD__
. '-' . $this->name
);
1020 wfProfileOut( __METHOD__
);
1025 * @see FileBackendStore::executeOpHandlesInternal()
1026 * @return Array List of corresponding Status objects
1027 * @throws MWException
1029 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1030 foreach ( $fileOpHandles as $fileOpHandle ) { // OK if empty
1031 throw new MWException( "This backend supports no asynchronous operations." );
1037 * @see FileBackend::clearCache()
1039 final public function clearCache( array $paths = null ) {
1040 if ( is_array( $paths ) ) {
1041 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1042 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1044 if ( $paths === null ) {
1045 $this->cache
= array();
1046 $this->expensiveCache
= array();
1048 foreach ( $paths as $path ) {
1049 unset( $this->cache
[$path] );
1050 unset( $this->expensiveCache
[$path] );
1053 $this->doClearCache( $paths );
1057 * Clears any additional stat caches for storage paths
1059 * @see FileBackend::clearCache()
1061 * @param $paths Array Storage paths (optional)
1064 protected function doClearCache( array $paths = null ) {}
1067 * Is this a key/value store where directories are just virtual?
1068 * Virtual directories exists in so much as files exists that are
1069 * prefixed with the directory path followed by a forward slash.
1073 abstract protected function directoriesAreVirtual();
1076 * Move a cache entry to the top (such as when accessed)
1078 * @param $path string Storage path
1081 protected function pingCache( $path ) {
1082 if ( isset( $this->cache
[$path] ) ) {
1083 $tmp = $this->cache
[$path];
1084 unset( $this->cache
[$path] );
1085 $this->cache
[$path] = $tmp;
1090 * Prune the inexpensive cache if it is too big to add an item
1094 protected function trimCache() {
1095 if ( count( $this->cache
) >= $this->maxCacheSize
) {
1096 reset( $this->cache
);
1097 unset( $this->cache
[key( $this->cache
)] );
1102 * Move a cache entry to the top (such as when accessed)
1104 * @param $path string Storage path
1107 protected function pingExpensiveCache( $path ) {
1108 if ( isset( $this->expensiveCache
[$path] ) ) {
1109 $tmp = $this->expensiveCache
[$path];
1110 unset( $this->expensiveCache
[$path] );
1111 $this->expensiveCache
[$path] = $tmp;
1116 * Prune the expensive cache if it is too big to add an item
1120 protected function trimExpensiveCache() {
1121 if ( count( $this->expensiveCache
) >= $this->maxExpensiveCacheSize
) {
1122 reset( $this->expensiveCache
);
1123 unset( $this->expensiveCache
[key( $this->expensiveCache
)] );
1128 * Check if a container name is valid.
1129 * This checks for for length and illegal characters.
1131 * @param $container string
1134 final protected static function isValidContainerName( $container ) {
1135 // This accounts for Swift and S3 restrictions while leaving room
1136 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1137 // This disallows directory separators or traversal characters.
1138 // Note that matching strings URL encode to the same string;
1139 // in Swift, the length restriction is *after* URL encoding.
1140 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1144 * Splits a storage path into an internal container name,
1145 * an internal relative file name, and a container shard suffix.
1146 * Any shard suffix is already appended to the internal container name.
1147 * This also checks that the storage path is valid and within this backend.
1149 * If the container is sharded but a suffix could not be determined,
1150 * this means that the path can only refer to a directory and can only
1151 * be scanned by looking in all the container shards.
1153 * @param $storagePath string
1154 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1156 final protected function resolveStoragePath( $storagePath ) {
1157 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1158 if ( $backend === $this->name
) { // must be for this backend
1159 $relPath = self
::normalizeContainerPath( $relPath );
1160 if ( $relPath !== null ) {
1161 // Get shard for the normalized path if this container is sharded
1162 $cShard = $this->getContainerShard( $container, $relPath );
1163 // Validate and sanitize the relative path (backend-specific)
1164 $relPath = $this->resolveContainerPath( $container, $relPath );
1165 if ( $relPath !== null ) {
1166 // Prepend any wiki ID prefix to the container name
1167 $container = $this->fullContainerName( $container );
1168 if ( self
::isValidContainerName( $container ) ) {
1169 // Validate and sanitize the container name (backend-specific)
1170 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1171 if ( $container !== null ) {
1172 return array( $container, $relPath, $cShard );
1178 return array( null, null, null );
1182 * Like resolveStoragePath() except null values are returned if
1183 * the container is sharded and the shard could not be determined.
1185 * @see FileBackendStore::resolveStoragePath()
1187 * @param $storagePath string
1188 * @return Array (container, path) or (null, null) if invalid
1190 final protected function resolveStoragePathReal( $storagePath ) {
1191 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1192 if ( $cShard !== null ) {
1193 return array( $container, $relPath );
1195 return array( null, null );
1199 * Get the container name shard suffix for a given path.
1200 * Any empty suffix means the container is not sharded.
1202 * @param $container string Container name
1203 * @param $relStoragePath string Storage path relative to the container
1204 * @return string|null Returns null if shard could not be determined
1206 final protected function getContainerShard( $container, $relPath ) {
1207 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1208 if ( $levels == 1 ||
$levels == 2 ) {
1209 // Hash characters are either base 16 or 36
1210 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1211 // Get a regex that represents the shard portion of paths.
1212 // The concatenation of the captures gives us the shard.
1213 if ( $levels === 1 ) { // 16 or 36 shards per container
1214 $hashDirRegex = '(' . $char . ')';
1215 } else { // 256 or 1296 shards per container
1216 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1217 $hashDirRegex = $char . '/(' . $char . '{2})';
1218 } else { // short hash dir format (e.g. "a/b/c")
1219 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1222 // Allow certain directories to be above the hash dirs so as
1223 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1224 // They must be 2+ chars to avoid any hash directory ambiguity.
1226 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1227 return '.' . implode( '', array_slice( $m, 1 ) );
1229 return null; // failed to match
1231 return ''; // no sharding
1235 * Check if a storage path maps to a single shard.
1236 * Container dirs like "a", where the container shards on "x/xy",
1237 * can reside on several shards. Such paths are tricky to handle.
1239 * @param $storagePath string Storage path
1242 final public function isSingleShardPathInternal( $storagePath ) {
1243 list( $c, $r, $shard ) = $this->resolveStoragePath( $storagePath );
1244 return ( $shard !== null );
1248 * Get the sharding config for a container.
1249 * If greater than 0, then all file storage paths within
1250 * the container are required to be hashed accordingly.
1252 * @param $container string
1253 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
1255 final protected function getContainerHashLevels( $container ) {
1256 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1257 $config = $this->shardViaHashLevels
[$container];
1258 $hashLevels = (int)$config['levels'];
1259 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1260 $hashBase = (int)$config['base'];
1261 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1262 return array( $hashLevels, $hashBase, $config['repeat'] );
1266 return array( 0, 0, false ); // no sharding
1270 * Get a list of full container shard suffixes for a container
1272 * @param $container string
1275 final protected function getContainerSuffixes( $container ) {
1277 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1278 if ( $digits > 0 ) {
1279 $numShards = pow( $base, $digits );
1280 for ( $index = 0; $index < $numShards; $index++
) {
1281 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1288 * Get the full container name, including the wiki ID prefix
1290 * @param $container string
1293 final protected function fullContainerName( $container ) {
1294 if ( $this->wikiId
!= '' ) {
1295 return "{$this->wikiId}-$container";
1302 * Resolve a container name, checking if it's allowed by the backend.
1303 * This is intended for internal use, such as encoding illegal chars.
1304 * Subclasses can override this to be more restrictive.
1306 * @param $container string
1307 * @return string|null
1309 protected function resolveContainerName( $container ) {
1314 * Resolve a relative storage path, checking if it's allowed by the backend.
1315 * This is intended for internal use, such as encoding illegal chars or perhaps
1316 * getting absolute paths (e.g. FS based backends). Note that the relative path
1317 * may be the empty string (e.g. the path is simply to the container).
1319 * @param $container string Container name
1320 * @param $relStoragePath string Storage path relative to the container
1321 * @return string|null Path or null if not valid
1323 protected function resolveContainerPath( $container, $relStoragePath ) {
1324 return $relStoragePath;
1328 * Get the cache key for a container
1330 * @param $container string Resolved container name
1333 private function containerCacheKey( $container ) {
1334 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1338 * Set the cached info for a container
1340 * @param $container string Resolved container name
1341 * @param $val mixed Information to cache
1344 final protected function setContainerCache( $container, $val ) {
1345 $this->memCache
->set( $this->containerCacheKey( $container ), $val, 14*86400 );
1349 * Delete the cached info for a container
1351 * @param $containers string Resolved container name
1354 final protected function deleteContainerCache( $container ) {
1355 if ( !$this->memCache
->delete( $this->containerCacheKey( $container ) ) ) {
1356 trigger_error( "Unable to delete stat cache for container $container." );
1361 * Do a batch lookup from cache for container stats for all containers
1362 * used in a list of container names, storage paths, or FileOp objects.
1364 * @param $items Array
1367 final protected function primeContainerCache( array $items ) {
1368 wfProfileIn( __METHOD__
);
1369 wfProfileIn( __METHOD__
. '-' . $this->name
);
1371 $paths = array(); // list of storage paths
1372 $contNames = array(); // (cache key => resolved container name)
1373 // Get all the paths/containers from the items...
1374 foreach ( $items as $item ) {
1375 if ( $item instanceof FileOp
) {
1376 $paths = array_merge( $paths, $item->storagePathsRead() );
1377 $paths = array_merge( $paths, $item->storagePathsChanged() );
1378 } elseif ( self
::isStoragePath( $item ) ) {
1380 } elseif ( is_string( $item ) ) { // full container name
1381 $contNames[$this->containerCacheKey( $item )] = $item;
1384 // Get all the corresponding cache keys for paths...
1385 foreach ( $paths as $path ) {
1386 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1387 if ( $fullCont !== null ) { // valid path for this backend
1388 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1392 $contInfo = array(); // (resolved container name => cache value)
1393 // Get all cache entries for these container cache keys...
1394 $values = $this->memCache
->getMulti( array_keys( $contNames ) );
1395 foreach ( $values as $cacheKey => $val ) {
1396 $contInfo[$contNames[$cacheKey]] = $val;
1399 // Populate the container process cache for the backend...
1400 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1402 wfProfileOut( __METHOD__
. '-' . $this->name
);
1403 wfProfileOut( __METHOD__
);
1407 * Fill the backend-specific process cache given an array of
1408 * resolved container names and their corresponding cached info.
1409 * Only containers that actually exist should appear in the map.
1411 * @param $containerInfo Array Map of resolved container names to cached info
1414 protected function doPrimeContainerCache( array $containerInfo ) {}
1417 * Get the cache key for a file path
1419 * @param $path string Storage path
1422 private function fileCacheKey( $path ) {
1423 return wfMemcKey( 'backend', $this->getName(), 'file', sha1( $path ) );
1427 * Set the cached stat info for a file path
1429 * @param $path string Storage path
1430 * @param $val mixed Information to cache
1433 final protected function setFileCache( $path, $val ) {
1434 $this->memCache
->set( $this->fileCacheKey( $path ), $val, 7*86400 );
1438 * Delete the cached stat info for a file path
1440 * @param $path string Storage path
1443 final protected function deleteFileCache( $path ) {
1444 if ( !$this->memCache
->delete( $this->fileCacheKey( $path ) ) ) {
1445 trigger_error( "Unable to delete stat cache for file $path." );
1450 * Do a batch lookup from cache for file stats for all paths
1451 * used in a list of storage paths or FileOp objects.
1453 * @param $items Array List of storage paths or FileOps
1456 final protected function primeFileCache( array $items ) {
1457 wfProfileIn( __METHOD__
);
1458 wfProfileIn( __METHOD__
. '-' . $this->name
);
1460 $paths = array(); // list of storage paths
1461 $pathNames = array(); // (cache key => storage path)
1462 // Get all the paths/containers from the items...
1463 foreach ( $items as $item ) {
1464 if ( $item instanceof FileOp
) {
1465 $paths = array_merge( $paths, $item->storagePathsRead() );
1466 $paths = array_merge( $paths, $item->storagePathsChanged() );
1467 } elseif ( self
::isStoragePath( $item ) ) {
1471 // Get all the corresponding cache keys for paths...
1472 foreach ( $paths as $path ) {
1473 list( $cont, $rel, $s ) = $this->resolveStoragePath( $path );
1474 if ( $rel !== null ) { // valid path for this backend
1475 $pathNames[$this->fileCacheKey( $path )] = $path;
1478 // Get all cache entries for these container cache keys...
1479 $values = $this->memCache
->getMulti( array_keys( $pathNames ) );
1480 foreach ( $values as $cacheKey => $val ) {
1481 if ( is_array( $val ) ) {
1482 $this->trimCache(); // limit memory
1483 $this->cache
[$pathNames[$cacheKey]]['stat'] = $val;
1487 wfProfileOut( __METHOD__
. '-' . $this->name
);
1488 wfProfileOut( __METHOD__
);
1493 * FileBackendStore helper class for performing asynchronous file operations.
1495 * For example, calling FileBackendStore::createInternal() with the "async"
1496 * param flag may result in a Status that contains this object as a value.
1497 * This class is largely backend-specific and is mostly just "magic" to be
1498 * passed to FileBackendStore::executeOpHandlesInternal().
1500 abstract class FileBackendStoreOpHandle
{
1502 public $params = array(); // params to caller functions
1503 /** @var FileBackendStore */
1506 public $resourcesToClose = array();
1508 public $call; // string; name that identifies the function called
1511 * Close all open file handles
1515 public function closeResources() {
1516 array_map( 'fclose', $this->resourcesToClose
);
1521 * FileBackendStore helper function to handle listings that span container shards.
1522 * Do not use this class from places outside of FileBackendStore.
1524 * @ingroup FileBackend
1526 abstract class FileBackendStoreShardListIterator
implements Iterator
{
1527 /** @var FileBackendStore */
1532 protected $shardSuffixes;
1533 protected $container; // string; full container name
1534 protected $directory; // string; resolved relative path
1536 /** @var Traversable */
1538 protected $curShard = 0; // integer
1539 protected $pos = 0; // integer
1542 protected $multiShardPaths = array(); // (rel path => 1)
1545 * @param $backend FileBackendStore
1546 * @param $container string Full storage container name
1547 * @param $dir string Storage directory relative to container
1548 * @param $suffixes Array List of container shard suffixes
1549 * @param $params Array
1551 public function __construct(
1552 FileBackendStore
$backend, $container, $dir, array $suffixes, array $params
1554 $this->backend
= $backend;
1555 $this->container
= $container;
1556 $this->directory
= $dir;
1557 $this->shardSuffixes
= $suffixes;
1558 $this->params
= $params;
1562 * @see Iterator::current()
1563 * @return string|bool String or false
1565 public function current() {
1566 if ( is_array( $this->iter
) ) {
1567 return current( $this->iter
);
1569 return $this->iter
->current();
1574 * @see Iterator::key()
1577 public function key() {
1582 * @see Iterator::next()
1585 public function next() {
1587 if ( is_array( $this->iter
) ) {
1588 next( $this->iter
);
1590 $this->iter
->next();
1592 // Filter out items that we already listed
1593 $this->filterViaNext();
1594 // Find the next non-empty shard if no elements are left
1595 $this->nextShardIteratorIfNotValid();
1599 * @see Iterator::rewind()
1602 public function rewind() {
1604 $this->curShard
= 0;
1605 $this->setIteratorFromCurrentShard();
1606 // Filter out items that we already listed
1607 $this->filterViaNext();
1608 // Find the next non-empty shard if this one has no elements
1609 $this->nextShardIteratorIfNotValid();
1613 * @see Iterator::valid()
1616 public function valid() {
1617 if ( $this->iter
=== null ) {
1618 return false; // some failure?
1619 } elseif ( is_array( $this->iter
) ) {
1620 return ( current( $this->iter
) !== false ); // no paths can have this value
1622 return $this->iter
->valid();
1627 * Filter out duplicate items by advancing to the next ones
1629 protected function filterViaNext() {
1630 while ( $this->iter
->valid() ) {
1631 $rel = $this->iter
->current(); // path relative to given directory
1632 $path = $this->params
['dir'] . "/{$rel}"; // full storage path
1633 if ( !$this->backend
->isSingleShardPathInternal( $path ) ) {
1634 // Don't keep listing paths that are on multiple shards
1635 if ( isset( $this->multiShardPaths
[$rel] ) ) {
1636 $this->iter
->next(); // we already listed this path
1638 $this->multiShardPaths
[$rel] = 1;
1646 * If the list iterator for this container shard is out of items,
1647 * then move on to the next container that has items.
1648 * If there are none, then it advances to the last container.
1650 protected function nextShardIteratorIfNotValid() {
1651 while ( !$this->valid() ) {
1652 if ( ++
$this->curShard
>= count( $this->shardSuffixes
) ) {
1653 break; // no more container shards
1655 $this->setIteratorFromCurrentShard();
1660 * Set the list iterator to that of the current container shard
1662 protected function setIteratorFromCurrentShard() {
1663 $suffix = $this->shardSuffixes
[$this->curShard
];
1664 $this->iter
= $this->listFromShard(
1665 "{$this->container}{$suffix}", $this->directory
, $this->params
);
1669 * Get the list for a given container shard
1671 * @param $container string Resolved container name
1672 * @param $dir string Resolved path relative to container
1673 * @param $params Array
1674 * @return Traversable|Array|null
1676 abstract protected function listFromShard( $container, $dir, array $params );
1680 * Iterator for listing directories
1682 class FileBackendStoreShardDirIterator
extends FileBackendStoreShardListIterator
{
1683 protected function listFromShard( $container, $dir, array $params ) {
1684 return $this->backend
->getDirectoryListInternal( $container, $dir, $params );
1689 * Iterator for listing regular files
1691 class FileBackendStoreShardFileIterator
extends FileBackendStoreShardListIterator
{
1692 protected function listFromShard( $container, $dir, array $params ) {
1693 return $this->backend
->getFileListInternal( $container, $dir, $params );