Merge "Depedencency cleanups to SwiftFileBackend"
[lhc/web/wiklou.git] / includes / libs / filebackend / FileBackendStore.php
1 <?php
2 /**
3 * Base class for all backends using particular storage medium.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup FileBackend
22 * @author Aaron Schulz
23 */
24
25 /**
26 * @brief Base class for all backends using particular storage medium.
27 *
28 * This class defines the methods as abstract that subclasses must implement.
29 * Outside callers should *not* use functions with "Internal" in the name.
30 *
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.
34 *
35 * @ingroup FileBackend
36 * @since 1.19
37 */
38 abstract class FileBackendStore extends FileBackend {
39 /** @var WANObjectCache */
40 protected $memCache;
41 /** @var BagOStuff */
42 protected $srvCache;
43 /** @var ProcessCacheLRU Map of paths to small (RAM/disk) cache items */
44 protected $cheapCache;
45 /** @var ProcessCacheLRU Map of paths to large (RAM/disk) cache items */
46 protected $expensiveCache;
47
48 /** @var array Map of container names to sharding config */
49 protected $shardViaHashLevels = [];
50
51 /** @var callable Method to get the MIME type of files */
52 protected $mimeCallback;
53
54 protected $maxFileSize = 4294967296; // integer bytes (4GiB)
55
56 const CACHE_TTL = 10; // integer; TTL in seconds for process cache entries
57 const CACHE_CHEAP_SIZE = 500; // integer; max entries in "cheap cache"
58 const CACHE_EXPENSIVE_SIZE = 5; // integer; max entries in "expensive cache"
59
60 /**
61 * @see FileBackend::__construct()
62 * Additional $config params include:
63 * - srvCache : BagOStuff cache to APC/XCache or the like.
64 * - wanCache : WANObjectCache object to use for persistent caching.
65 * - mimeCallback : Callback that takes (storage path, content, file system path) and
66 * returns the MIME type of the file or 'unknown/unknown'. The file
67 * system path parameter should be used if the content one is null.
68 *
69 * @param array $config
70 */
71 public function __construct( array $config ) {
72 parent::__construct( $config );
73 $this->mimeCallback = isset( $config['mimeCallback'] )
74 ? $config['mimeCallback']
75 : null;
76 $this->srvCache = new EmptyBagOStuff(); // disabled by default
77 $this->memCache = WANObjectCache::newEmpty(); // disabled by default
78 $this->cheapCache = new ProcessCacheLRU( self::CACHE_CHEAP_SIZE );
79 $this->expensiveCache = new ProcessCacheLRU( self::CACHE_EXPENSIVE_SIZE );
80 }
81
82 /**
83 * Get the maximum allowable file size given backend
84 * medium restrictions and basic performance constraints.
85 * Do not call this function from places outside FileBackend and FileOp.
86 *
87 * @return int Bytes
88 */
89 final public function maxFileSizeInternal() {
90 return $this->maxFileSize;
91 }
92
93 /**
94 * Check if a file can be created or changed at a given storage path.
95 * FS backends should check if the parent directory exists, files can be
96 * written under it, and that any file already there is writable.
97 * Backends using key/value stores should check if the container exists.
98 *
99 * @param string $storagePath
100 * @return bool
101 */
102 abstract public function isPathUsableInternal( $storagePath );
103
104 /**
105 * Create a file in the backend with the given contents.
106 * This will overwrite any file that exists at the destination.
107 * Do not call this function from places outside FileBackend and FileOp.
108 *
109 * $params include:
110 * - content : the raw file contents
111 * - dst : destination storage path
112 * - headers : HTTP header name/value map
113 * - async : StatusValue will be returned immediately if supported.
114 * If the StatusValue is OK, then its value field will be
115 * set to a FileBackendStoreOpHandle object.
116 * - dstExists : Whether a file exists at the destination (optimization).
117 * Callers can use "false" if no existing file is being changed.
118 *
119 * @param array $params
120 * @return StatusValue
121 */
122 final public function createInternal( array $params ) {
123 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
124 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
125 $status = $this->newStatus( 'backend-fail-maxsize',
126 $params['dst'], $this->maxFileSizeInternal() );
127 } else {
128 $status = $this->doCreateInternal( $params );
129 $this->clearCache( [ $params['dst'] ] );
130 if ( !isset( $params['dstExists'] ) || $params['dstExists'] ) {
131 $this->deleteFileCache( $params['dst'] ); // persistent cache
132 }
133 }
134
135 return $status;
136 }
137
138 /**
139 * @see FileBackendStore::createInternal()
140 * @param array $params
141 * @return StatusValue
142 */
143 abstract protected function doCreateInternal( array $params );
144
145 /**
146 * Store a file into the backend from a file on disk.
147 * This will overwrite any file that exists at the destination.
148 * Do not call this function from places outside FileBackend and FileOp.
149 *
150 * $params include:
151 * - src : source path on disk
152 * - dst : destination storage path
153 * - headers : HTTP header name/value map
154 * - async : StatusValue will be returned immediately if supported.
155 * If the StatusValue is OK, then its value field will be
156 * set to a FileBackendStoreOpHandle object.
157 * - dstExists : Whether a file exists at the destination (optimization).
158 * Callers can use "false" if no existing file is being changed.
159 *
160 * @param array $params
161 * @return StatusValue
162 */
163 final public function storeInternal( array $params ) {
164 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
165 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
166 $status = $this->newStatus( 'backend-fail-maxsize',
167 $params['dst'], $this->maxFileSizeInternal() );
168 } else {
169 $status = $this->doStoreInternal( $params );
170 $this->clearCache( [ $params['dst'] ] );
171 if ( !isset( $params['dstExists'] ) || $params['dstExists'] ) {
172 $this->deleteFileCache( $params['dst'] ); // persistent cache
173 }
174 }
175
176 return $status;
177 }
178
179 /**
180 * @see FileBackendStore::storeInternal()
181 * @param array $params
182 * @return StatusValue
183 */
184 abstract protected function doStoreInternal( array $params );
185
186 /**
187 * Copy a file from one storage path to another in the backend.
188 * This will overwrite any file that exists at the destination.
189 * Do not call this function from places outside FileBackend and FileOp.
190 *
191 * $params include:
192 * - src : source storage path
193 * - dst : destination storage path
194 * - ignoreMissingSource : do nothing if the source file does not exist
195 * - headers : HTTP header name/value map
196 * - async : StatusValue will be returned immediately if supported.
197 * If the StatusValue is OK, then its value field will be
198 * set to a FileBackendStoreOpHandle object.
199 * - dstExists : Whether a file exists at the destination (optimization).
200 * Callers can use "false" if no existing file is being changed.
201 *
202 * @param array $params
203 * @return StatusValue
204 */
205 final public function copyInternal( array $params ) {
206 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
207 $status = $this->doCopyInternal( $params );
208 $this->clearCache( [ $params['dst'] ] );
209 if ( !isset( $params['dstExists'] ) || $params['dstExists'] ) {
210 $this->deleteFileCache( $params['dst'] ); // persistent cache
211 }
212
213 return $status;
214 }
215
216 /**
217 * @see FileBackendStore::copyInternal()
218 * @param array $params
219 * @return StatusValue
220 */
221 abstract protected function doCopyInternal( array $params );
222
223 /**
224 * Delete a file at the storage path.
225 * Do not call this function from places outside FileBackend and FileOp.
226 *
227 * $params include:
228 * - src : source storage path
229 * - ignoreMissingSource : do nothing if the source file does not exist
230 * - async : StatusValue will be returned immediately if supported.
231 * If the StatusValue is OK, then its value field will be
232 * set to a FileBackendStoreOpHandle object.
233 *
234 * @param array $params
235 * @return StatusValue
236 */
237 final public function deleteInternal( array $params ) {
238 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
239 $status = $this->doDeleteInternal( $params );
240 $this->clearCache( [ $params['src'] ] );
241 $this->deleteFileCache( $params['src'] ); // persistent cache
242 return $status;
243 }
244
245 /**
246 * @see FileBackendStore::deleteInternal()
247 * @param array $params
248 * @return StatusValue
249 */
250 abstract protected function doDeleteInternal( array $params );
251
252 /**
253 * Move a file from one storage path to another in the backend.
254 * This will overwrite any file that exists at the destination.
255 * Do not call this function from places outside FileBackend and FileOp.
256 *
257 * $params include:
258 * - src : source storage path
259 * - dst : destination storage path
260 * - ignoreMissingSource : do nothing if the source file does not exist
261 * - headers : HTTP header name/value map
262 * - async : StatusValue will be returned immediately if supported.
263 * If the StatusValue is OK, then its value field will be
264 * set to a FileBackendStoreOpHandle object.
265 * - dstExists : Whether a file exists at the destination (optimization).
266 * Callers can use "false" if no existing file is being changed.
267 *
268 * @param array $params
269 * @return StatusValue
270 */
271 final public function moveInternal( array $params ) {
272 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
273 $status = $this->doMoveInternal( $params );
274 $this->clearCache( [ $params['src'], $params['dst'] ] );
275 $this->deleteFileCache( $params['src'] ); // persistent cache
276 if ( !isset( $params['dstExists'] ) || $params['dstExists'] ) {
277 $this->deleteFileCache( $params['dst'] ); // persistent cache
278 }
279
280 return $status;
281 }
282
283 /**
284 * @see FileBackendStore::moveInternal()
285 * @param array $params
286 * @return StatusValue
287 */
288 protected function doMoveInternal( array $params ) {
289 unset( $params['async'] ); // two steps, won't work here :)
290 $nsrc = FileBackend::normalizeStoragePath( $params['src'] );
291 $ndst = FileBackend::normalizeStoragePath( $params['dst'] );
292 // Copy source to dest
293 $status = $this->copyInternal( $params );
294 if ( $nsrc !== $ndst && $status->isOK() ) {
295 // Delete source (only fails due to races or network problems)
296 $status->merge( $this->deleteInternal( [ 'src' => $params['src'] ] ) );
297 $status->setResult( true, $status->value ); // ignore delete() errors
298 }
299
300 return $status;
301 }
302
303 /**
304 * Alter metadata for a file at the storage path.
305 * Do not call this function from places outside FileBackend and FileOp.
306 *
307 * $params include:
308 * - src : source storage path
309 * - headers : HTTP header name/value map
310 * - async : StatusValue will be returned immediately if supported.
311 * If the StatusValue is OK, then its value field will be
312 * set to a FileBackendStoreOpHandle object.
313 *
314 * @param array $params
315 * @return StatusValue
316 */
317 final public function describeInternal( array $params ) {
318 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
319 if ( count( $params['headers'] ) ) {
320 $status = $this->doDescribeInternal( $params );
321 $this->clearCache( [ $params['src'] ] );
322 $this->deleteFileCache( $params['src'] ); // persistent cache
323 } else {
324 $status = $this->newStatus(); // nothing to do
325 }
326
327 return $status;
328 }
329
330 /**
331 * @see FileBackendStore::describeInternal()
332 * @param array $params
333 * @return StatusValue
334 */
335 protected function doDescribeInternal( array $params ) {
336 return $this->newStatus();
337 }
338
339 /**
340 * No-op file operation that does nothing.
341 * Do not call this function from places outside FileBackend and FileOp.
342 *
343 * @param array $params
344 * @return StatusValue
345 */
346 final public function nullInternal( array $params ) {
347 return $this->newStatus();
348 }
349
350 final public function concatenate( array $params ) {
351 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
352 $status = $this->newStatus();
353
354 // Try to lock the source files for the scope of this function
355 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager::LOCK_UW, $status );
356 if ( $status->isOK() ) {
357 // Actually do the file concatenation...
358 $start_time = microtime( true );
359 $status->merge( $this->doConcatenate( $params ) );
360 $sec = microtime( true ) - $start_time;
361 if ( !$status->isOK() ) {
362 $this->logger->error( get_class( $this ) . "-{$this->name}" .
363 " failed to concatenate " . count( $params['srcs'] ) . " file(s) [$sec sec]" );
364 }
365 }
366
367 return $status;
368 }
369
370 /**
371 * @see FileBackendStore::concatenate()
372 * @param array $params
373 * @return StatusValue
374 */
375 protected function doConcatenate( array $params ) {
376 $status = $this->newStatus();
377 $tmpPath = $params['dst']; // convenience
378 unset( $params['latest'] ); // sanity
379
380 // Check that the specified temp file is valid...
381 MediaWiki\suppressWarnings();
382 $ok = ( is_file( $tmpPath ) && filesize( $tmpPath ) == 0 );
383 MediaWiki\restoreWarnings();
384 if ( !$ok ) { // not present or not empty
385 $status->fatal( 'backend-fail-opentemp', $tmpPath );
386
387 return $status;
388 }
389
390 // Get local FS versions of the chunks needed for the concatenation...
391 $fsFiles = $this->getLocalReferenceMulti( $params );
392 foreach ( $fsFiles as $path => &$fsFile ) {
393 if ( !$fsFile ) { // chunk failed to download?
394 $fsFile = $this->getLocalReference( [ 'src' => $path ] );
395 if ( !$fsFile ) { // retry failed?
396 $status->fatal( 'backend-fail-read', $path );
397
398 return $status;
399 }
400 }
401 }
402 unset( $fsFile ); // unset reference so we can reuse $fsFile
403
404 // Get a handle for the destination temp file
405 $tmpHandle = fopen( $tmpPath, 'ab' );
406 if ( $tmpHandle === false ) {
407 $status->fatal( 'backend-fail-opentemp', $tmpPath );
408
409 return $status;
410 }
411
412 // Build up the temp file using the source chunks (in order)...
413 foreach ( $fsFiles as $virtualSource => $fsFile ) {
414 // Get a handle to the local FS version
415 $sourceHandle = fopen( $fsFile->getPath(), 'rb' );
416 if ( $sourceHandle === false ) {
417 fclose( $tmpHandle );
418 $status->fatal( 'backend-fail-read', $virtualSource );
419
420 return $status;
421 }
422 // Append chunk to file (pass chunk size to avoid magic quotes)
423 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
424 fclose( $sourceHandle );
425 fclose( $tmpHandle );
426 $status->fatal( 'backend-fail-writetemp', $tmpPath );
427
428 return $status;
429 }
430 fclose( $sourceHandle );
431 }
432 if ( !fclose( $tmpHandle ) ) {
433 $status->fatal( 'backend-fail-closetemp', $tmpPath );
434
435 return $status;
436 }
437
438 clearstatcache(); // temp file changed
439
440 return $status;
441 }
442
443 final protected function doPrepare( array $params ) {
444 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
445 $status = $this->newStatus();
446
447 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
448 if ( $dir === null ) {
449 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
450
451 return $status; // invalid storage path
452 }
453
454 if ( $shard !== null ) { // confined to a single container/shard
455 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
456 } else { // directory is on several shards
457 $this->logger->debug( __METHOD__ . ": iterating over all container shards.\n" );
458 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
459 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
460 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
461 }
462 }
463
464 return $status;
465 }
466
467 /**
468 * @see FileBackendStore::doPrepare()
469 * @param string $container
470 * @param string $dir
471 * @param array $params
472 * @return StatusValue
473 */
474 protected function doPrepareInternal( $container, $dir, array $params ) {
475 return $this->newStatus();
476 }
477
478 final protected function doSecure( array $params ) {
479 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
480 $status = $this->newStatus();
481
482 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
483 if ( $dir === null ) {
484 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
485
486 return $status; // invalid storage path
487 }
488
489 if ( $shard !== null ) { // confined to a single container/shard
490 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
491 } else { // directory is on several shards
492 $this->logger->debug( __METHOD__ . ": iterating over all container shards.\n" );
493 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
494 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
495 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
496 }
497 }
498
499 return $status;
500 }
501
502 /**
503 * @see FileBackendStore::doSecure()
504 * @param string $container
505 * @param string $dir
506 * @param array $params
507 * @return StatusValue
508 */
509 protected function doSecureInternal( $container, $dir, array $params ) {
510 return $this->newStatus();
511 }
512
513 final protected function doPublish( array $params ) {
514 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
515 $status = $this->newStatus();
516
517 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
518 if ( $dir === null ) {
519 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
520
521 return $status; // invalid storage path
522 }
523
524 if ( $shard !== null ) { // confined to a single container/shard
525 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
526 } else { // directory is on several shards
527 $this->logger->debug( __METHOD__ . ": iterating over all container shards.\n" );
528 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
529 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
530 $status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
531 }
532 }
533
534 return $status;
535 }
536
537 /**
538 * @see FileBackendStore::doPublish()
539 * @param string $container
540 * @param string $dir
541 * @param array $params
542 * @return StatusValue
543 */
544 protected function doPublishInternal( $container, $dir, array $params ) {
545 return $this->newStatus();
546 }
547
548 final protected function doClean( array $params ) {
549 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
550 $status = $this->newStatus();
551
552 // Recursive: first delete all empty subdirs recursively
553 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
554 $subDirsRel = $this->getTopDirectoryList( [ 'dir' => $params['dir'] ] );
555 if ( $subDirsRel !== null ) { // no errors
556 foreach ( $subDirsRel as $subDirRel ) {
557 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
558 $status->merge( $this->doClean( [ 'dir' => $subDir ] + $params ) );
559 }
560 unset( $subDirsRel ); // free directory for rmdir() on Windows (for FS backends)
561 }
562 }
563
564 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
565 if ( $dir === null ) {
566 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
567
568 return $status; // invalid storage path
569 }
570
571 // Attempt to lock this directory...
572 $filesLockEx = [ $params['dir'] ];
573 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager::LOCK_EX, $status );
574 if ( !$status->isOK() ) {
575 return $status; // abort
576 }
577
578 if ( $shard !== null ) { // confined to a single container/shard
579 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
580 $this->deleteContainerCache( $fullCont ); // purge cache
581 } else { // directory is on several shards
582 $this->logger->debug( __METHOD__ . ": iterating over all container shards.\n" );
583 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
584 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
585 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
586 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
587 }
588 }
589
590 return $status;
591 }
592
593 /**
594 * @see FileBackendStore::doClean()
595 * @param string $container
596 * @param string $dir
597 * @param array $params
598 * @return StatusValue
599 */
600 protected function doCleanInternal( $container, $dir, array $params ) {
601 return $this->newStatus();
602 }
603
604 final public function fileExists( array $params ) {
605 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
606 $stat = $this->getFileStat( $params );
607
608 return ( $stat === null ) ? null : (bool)$stat; // null => failure
609 }
610
611 final public function getFileTimestamp( array $params ) {
612 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
613 $stat = $this->getFileStat( $params );
614
615 return $stat ? $stat['mtime'] : false;
616 }
617
618 final public function getFileSize( array $params ) {
619 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
620 $stat = $this->getFileStat( $params );
621
622 return $stat ? $stat['size'] : false;
623 }
624
625 final public function getFileStat( array $params ) {
626 $path = self::normalizeStoragePath( $params['src'] );
627 if ( $path === null ) {
628 return false; // invalid storage path
629 }
630 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
631 $latest = !empty( $params['latest'] ); // use latest data?
632 if ( !$latest && !$this->cheapCache->has( $path, 'stat', self::CACHE_TTL ) ) {
633 $this->primeFileCache( [ $path ] ); // check persistent cache
634 }
635 if ( $this->cheapCache->has( $path, 'stat', self::CACHE_TTL ) ) {
636 $stat = $this->cheapCache->get( $path, 'stat' );
637 // If we want the latest data, check that this cached
638 // value was in fact fetched with the latest available data.
639 if ( is_array( $stat ) ) {
640 if ( !$latest || $stat['latest'] ) {
641 return $stat;
642 }
643 } elseif ( in_array( $stat, [ 'NOT_EXIST', 'NOT_EXIST_LATEST' ] ) ) {
644 if ( !$latest || $stat === 'NOT_EXIST_LATEST' ) {
645 return false;
646 }
647 }
648 }
649 $stat = $this->doGetFileStat( $params );
650 if ( is_array( $stat ) ) { // file exists
651 // Strongly consistent backends can automatically set "latest"
652 $stat['latest'] = isset( $stat['latest'] ) ? $stat['latest'] : $latest;
653 $this->cheapCache->set( $path, 'stat', $stat );
654 $this->setFileCache( $path, $stat ); // update persistent cache
655 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
656 $this->cheapCache->set( $path, 'sha1',
657 [ 'hash' => $stat['sha1'], 'latest' => $latest ] );
658 }
659 if ( isset( $stat['xattr'] ) ) { // some backends store headers/metadata
660 $stat['xattr'] = self::normalizeXAttributes( $stat['xattr'] );
661 $this->cheapCache->set( $path, 'xattr',
662 [ 'map' => $stat['xattr'], 'latest' => $latest ] );
663 }
664 } elseif ( $stat === false ) { // file does not exist
665 $this->cheapCache->set( $path, 'stat', $latest ? 'NOT_EXIST_LATEST' : 'NOT_EXIST' );
666 $this->cheapCache->set( $path, 'xattr', [ 'map' => false, 'latest' => $latest ] );
667 $this->cheapCache->set( $path, 'sha1', [ 'hash' => false, 'latest' => $latest ] );
668 $this->logger->debug( __METHOD__ . ": File $path does not exist.\n" );
669 } else { // an error occurred
670 $this->logger->warning( __METHOD__ . ": Could not stat file $path.\n" );
671 }
672
673 return $stat;
674 }
675
676 /**
677 * @see FileBackendStore::getFileStat()
678 */
679 abstract protected function doGetFileStat( array $params );
680
681 public function getFileContentsMulti( array $params ) {
682 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
683
684 $params = $this->setConcurrencyFlags( $params );
685 $contents = $this->doGetFileContentsMulti( $params );
686
687 return $contents;
688 }
689
690 /**
691 * @see FileBackendStore::getFileContentsMulti()
692 * @param array $params
693 * @return array
694 */
695 protected function doGetFileContentsMulti( array $params ) {
696 $contents = [];
697 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
698 MediaWiki\suppressWarnings();
699 $contents[$path] = $fsFile ? file_get_contents( $fsFile->getPath() ) : false;
700 MediaWiki\restoreWarnings();
701 }
702
703 return $contents;
704 }
705
706 final public function getFileXAttributes( array $params ) {
707 $path = self::normalizeStoragePath( $params['src'] );
708 if ( $path === null ) {
709 return false; // invalid storage path
710 }
711 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
712 $latest = !empty( $params['latest'] ); // use latest data?
713 if ( $this->cheapCache->has( $path, 'xattr', self::CACHE_TTL ) ) {
714 $stat = $this->cheapCache->get( $path, 'xattr' );
715 // If we want the latest data, check that this cached
716 // value was in fact fetched with the latest available data.
717 if ( !$latest || $stat['latest'] ) {
718 return $stat['map'];
719 }
720 }
721 $fields = $this->doGetFileXAttributes( $params );
722 $fields = is_array( $fields ) ? self::normalizeXAttributes( $fields ) : false;
723 $this->cheapCache->set( $path, 'xattr', [ 'map' => $fields, 'latest' => $latest ] );
724
725 return $fields;
726 }
727
728 /**
729 * @see FileBackendStore::getFileXAttributes()
730 * @return bool|string
731 */
732 protected function doGetFileXAttributes( array $params ) {
733 return [ 'headers' => [], 'metadata' => [] ]; // not supported
734 }
735
736 final public function getFileSha1Base36( array $params ) {
737 $path = self::normalizeStoragePath( $params['src'] );
738 if ( $path === null ) {
739 return false; // invalid storage path
740 }
741 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
742 $latest = !empty( $params['latest'] ); // use latest data?
743 if ( $this->cheapCache->has( $path, 'sha1', self::CACHE_TTL ) ) {
744 $stat = $this->cheapCache->get( $path, 'sha1' );
745 // If we want the latest data, check that this cached
746 // value was in fact fetched with the latest available data.
747 if ( !$latest || $stat['latest'] ) {
748 return $stat['hash'];
749 }
750 }
751 $hash = $this->doGetFileSha1Base36( $params );
752 $this->cheapCache->set( $path, 'sha1', [ 'hash' => $hash, 'latest' => $latest ] );
753
754 return $hash;
755 }
756
757 /**
758 * @see FileBackendStore::getFileSha1Base36()
759 * @param array $params
760 * @return bool|string
761 */
762 protected function doGetFileSha1Base36( array $params ) {
763 $fsFile = $this->getLocalReference( $params );
764 if ( !$fsFile ) {
765 return false;
766 } else {
767 return $fsFile->getSha1Base36();
768 }
769 }
770
771 final public function getFileProps( array $params ) {
772 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
773 $fsFile = $this->getLocalReference( $params );
774 $props = $fsFile ? $fsFile->getProps() : FSFile::placeholderProps();
775
776 return $props;
777 }
778
779 final public function getLocalReferenceMulti( array $params ) {
780 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
781
782 $params = $this->setConcurrencyFlags( $params );
783
784 $fsFiles = []; // (path => FSFile)
785 $latest = !empty( $params['latest'] ); // use latest data?
786 // Reuse any files already in process cache...
787 foreach ( $params['srcs'] as $src ) {
788 $path = self::normalizeStoragePath( $src );
789 if ( $path === null ) {
790 $fsFiles[$src] = null; // invalid storage path
791 } elseif ( $this->expensiveCache->has( $path, 'localRef' ) ) {
792 $val = $this->expensiveCache->get( $path, 'localRef' );
793 // If we want the latest data, check that this cached
794 // value was in fact fetched with the latest available data.
795 if ( !$latest || $val['latest'] ) {
796 $fsFiles[$src] = $val['object'];
797 }
798 }
799 }
800 // Fetch local references of any remaning files...
801 $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
802 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
803 $fsFiles[$path] = $fsFile;
804 if ( $fsFile ) { // update the process cache...
805 $this->expensiveCache->set( $path, 'localRef',
806 [ 'object' => $fsFile, 'latest' => $latest ] );
807 }
808 }
809
810 return $fsFiles;
811 }
812
813 /**
814 * @see FileBackendStore::getLocalReferenceMulti()
815 * @param array $params
816 * @return array
817 */
818 protected function doGetLocalReferenceMulti( array $params ) {
819 return $this->doGetLocalCopyMulti( $params );
820 }
821
822 final public function getLocalCopyMulti( array $params ) {
823 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
824
825 $params = $this->setConcurrencyFlags( $params );
826 $tmpFiles = $this->doGetLocalCopyMulti( $params );
827
828 return $tmpFiles;
829 }
830
831 /**
832 * @see FileBackendStore::getLocalCopyMulti()
833 * @param array $params
834 * @return array
835 */
836 abstract protected function doGetLocalCopyMulti( array $params );
837
838 /**
839 * @see FileBackend::getFileHttpUrl()
840 * @param array $params
841 * @return string|null
842 */
843 public function getFileHttpUrl( array $params ) {
844 return null; // not supported
845 }
846
847 final public function streamFile( array $params ) {
848 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
849 $status = $this->newStatus();
850
851 // Always set some fields for subclass convenience
852 $params['options'] = isset( $params['options'] ) ? $params['options'] : [];
853 $params['headers'] = isset( $params['headers'] ) ? $params['headers'] : [];
854
855 // Don't stream it out as text/html if there was a PHP error
856 if ( ( empty( $params['headless'] ) || $params['headers'] ) && headers_sent() ) {
857 print "Headers already sent, terminating.\n";
858 $status->fatal( 'backend-fail-stream', $params['src'] );
859 return $status;
860 }
861
862 $status->merge( $this->doStreamFile( $params ) );
863
864 return $status;
865 }
866
867 /**
868 * @see FileBackendStore::streamFile()
869 * @param array $params
870 * @return StatusValue
871 */
872 protected function doStreamFile( array $params ) {
873 $status = $this->newStatus();
874
875 $flags = 0;
876 $flags |= !empty( $params['headless'] ) ? HTTPFileStreamer::STREAM_HEADLESS : 0;
877 $flags |= !empty( $params['allowOB'] ) ? HTTPFileStreamer::STREAM_ALLOW_OB : 0;
878
879 $fsFile = $this->getLocalReference( $params );
880 if ( $fsFile ) {
881 $streamer = new HTTPFileStreamer(
882 $fsFile->getPath(),
883 [
884 'obResetFunc' => $this->obResetFunc,
885 'streamMimeFunc' => $this->streamMimeFunc
886 ]
887 );
888 $res = $streamer->stream( $params['headers'], true, $params['options'], $flags );
889 } else {
890 $res = false;
891 HTTPFileStreamer::send404Message( $params['src'], $flags );
892 }
893
894 if ( !$res ) {
895 $status->fatal( 'backend-fail-stream', $params['src'] );
896 }
897
898 return $status;
899 }
900
901 final public function directoryExists( array $params ) {
902 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
903 if ( $dir === null ) {
904 return false; // invalid storage path
905 }
906 if ( $shard !== null ) { // confined to a single container/shard
907 return $this->doDirectoryExists( $fullCont, $dir, $params );
908 } else { // directory is on several shards
909 $this->logger->debug( __METHOD__ . ": iterating over all container shards.\n" );
910 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
911 $res = false; // response
912 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
913 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
914 if ( $exists ) {
915 $res = true;
916 break; // found one!
917 } elseif ( $exists === null ) { // error?
918 $res = null; // if we don't find anything, it is indeterminate
919 }
920 }
921
922 return $res;
923 }
924 }
925
926 /**
927 * @see FileBackendStore::directoryExists()
928 *
929 * @param string $container Resolved container name
930 * @param string $dir Resolved path relative to container
931 * @param array $params
932 * @return bool|null
933 */
934 abstract protected function doDirectoryExists( $container, $dir, array $params );
935
936 final public function getDirectoryList( array $params ) {
937 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
938 if ( $dir === null ) { // invalid storage path
939 return null;
940 }
941 if ( $shard !== null ) {
942 // File listing is confined to a single container/shard
943 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
944 } else {
945 $this->logger->debug( __METHOD__ . ": iterating over all container shards.\n" );
946 // File listing spans multiple containers/shards
947 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
948
949 return new FileBackendStoreShardDirIterator( $this,
950 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
951 }
952 }
953
954 /**
955 * Do not call this function from places outside FileBackend
956 *
957 * @see FileBackendStore::getDirectoryList()
958 *
959 * @param string $container Resolved container name
960 * @param string $dir Resolved path relative to container
961 * @param array $params
962 * @return Traversable|array|null Returns null on failure
963 */
964 abstract public function getDirectoryListInternal( $container, $dir, array $params );
965
966 final public function getFileList( array $params ) {
967 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
968 if ( $dir === null ) { // invalid storage path
969 return null;
970 }
971 if ( $shard !== null ) {
972 // File listing is confined to a single container/shard
973 return $this->getFileListInternal( $fullCont, $dir, $params );
974 } else {
975 $this->logger->debug( __METHOD__ . ": iterating over all container shards.\n" );
976 // File listing spans multiple containers/shards
977 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
978
979 return new FileBackendStoreShardFileIterator( $this,
980 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
981 }
982 }
983
984 /**
985 * Do not call this function from places outside FileBackend
986 *
987 * @see FileBackendStore::getFileList()
988 *
989 * @param string $container Resolved container name
990 * @param string $dir Resolved path relative to container
991 * @param array $params
992 * @return Traversable|array|null Returns null on failure
993 */
994 abstract public function getFileListInternal( $container, $dir, array $params );
995
996 /**
997 * Return a list of FileOp objects from a list of operations.
998 * Do not call this function from places outside FileBackend.
999 *
1000 * The result must have the same number of items as the input.
1001 * An exception is thrown if an unsupported operation is requested.
1002 *
1003 * @param array $ops Same format as doOperations()
1004 * @return FileOp[] List of FileOp objects
1005 * @throws FileBackendError
1006 */
1007 final public function getOperationsInternal( array $ops ) {
1008 $supportedOps = [
1009 'store' => 'StoreFileOp',
1010 'copy' => 'CopyFileOp',
1011 'move' => 'MoveFileOp',
1012 'delete' => 'DeleteFileOp',
1013 'create' => 'CreateFileOp',
1014 'describe' => 'DescribeFileOp',
1015 'null' => 'NullFileOp'
1016 ];
1017
1018 $performOps = []; // array of FileOp objects
1019 // Build up ordered array of FileOps...
1020 foreach ( $ops as $operation ) {
1021 $opName = $operation['op'];
1022 if ( isset( $supportedOps[$opName] ) ) {
1023 $class = $supportedOps[$opName];
1024 // Get params for this operation
1025 $params = $operation;
1026 // Append the FileOp class
1027 $performOps[] = new $class( $this, $params, $this->logger );
1028 } else {
1029 throw new FileBackendError( "Operation '$opName' is not supported." );
1030 }
1031 }
1032
1033 return $performOps;
1034 }
1035
1036 /**
1037 * Get a list of storage paths to lock for a list of operations
1038 * Returns an array with LockManager::LOCK_UW (shared locks) and
1039 * LockManager::LOCK_EX (exclusive locks) keys, each corresponding
1040 * to a list of storage paths to be locked. All returned paths are
1041 * normalized.
1042 *
1043 * @param array $performOps List of FileOp objects
1044 * @return array (LockManager::LOCK_UW => path list, LockManager::LOCK_EX => path list)
1045 */
1046 final public function getPathsToLockForOpsInternal( array $performOps ) {
1047 // Build up a list of files to lock...
1048 $paths = [ 'sh' => [], 'ex' => [] ];
1049 foreach ( $performOps as $fileOp ) {
1050 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1051 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1052 }
1053 // Optimization: if doing an EX lock anyway, don't also set an SH one
1054 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1055 // Get a shared lock on the parent directory of each path changed
1056 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1057
1058 return [
1059 LockManager::LOCK_UW => $paths['sh'],
1060 LockManager::LOCK_EX => $paths['ex']
1061 ];
1062 }
1063
1064 public function getScopedLocksForOps( array $ops, StatusValue $status ) {
1065 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1066
1067 return $this->getScopedFileLocks( $paths, 'mixed', $status );
1068 }
1069
1070 final protected function doOperationsInternal( array $ops, array $opts ) {
1071 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1072 $status = $this->newStatus();
1073
1074 // Fix up custom header name/value pairs...
1075 $ops = array_map( [ $this, 'sanitizeOpHeaders' ], $ops );
1076
1077 // Build up a list of FileOps...
1078 $performOps = $this->getOperationsInternal( $ops );
1079
1080 // Acquire any locks as needed...
1081 if ( empty( $opts['nonLocking'] ) ) {
1082 // Build up a list of files to lock...
1083 $paths = $this->getPathsToLockForOpsInternal( $performOps );
1084 // Try to lock those files for the scope of this function...
1085
1086 $scopeLock = $this->getScopedFileLocks( $paths, 'mixed', $status );
1087 if ( !$status->isOK() ) {
1088 return $status; // abort
1089 }
1090 }
1091
1092 // Clear any file cache entries (after locks acquired)
1093 if ( empty( $opts['preserveCache'] ) ) {
1094 $this->clearCache();
1095 }
1096
1097 // Build the list of paths involved
1098 $paths = [];
1099 foreach ( $performOps as $op ) {
1100 $paths = array_merge( $paths, $op->storagePathsRead() );
1101 $paths = array_merge( $paths, $op->storagePathsChanged() );
1102 }
1103
1104 // Enlarge the cache to fit the stat entries of these files
1105 $this->cheapCache->resize( max( 2 * count( $paths ), self::CACHE_CHEAP_SIZE ) );
1106
1107 // Load from the persistent container caches
1108 $this->primeContainerCache( $paths );
1109 // Get the latest stat info for all the files (having locked them)
1110 $ok = $this->preloadFileStat( [ 'srcs' => $paths, 'latest' => true ] );
1111
1112 if ( $ok ) {
1113 // Actually attempt the operation batch...
1114 $opts = $this->setConcurrencyFlags( $opts );
1115 $subStatus = FileOpBatch::attempt( $performOps, $opts, $this->fileJournal );
1116 } else {
1117 // If we could not even stat some files, then bail out...
1118 $subStatus = $this->newStatus( 'backend-fail-internal', $this->name );
1119 foreach ( $ops as $i => $op ) { // mark each op as failed
1120 $subStatus->success[$i] = false;
1121 ++$subStatus->failCount;
1122 }
1123 $this->logger->error( get_class( $this ) . "-{$this->name} " .
1124 " stat failure; aborted operations: " . FormatJson::encode( $ops ) );
1125 }
1126
1127 // Merge errors into StatusValue fields
1128 $status->merge( $subStatus );
1129 $status->success = $subStatus->success; // not done in merge()
1130
1131 // Shrink the stat cache back to normal size
1132 $this->cheapCache->resize( self::CACHE_CHEAP_SIZE );
1133
1134 return $status;
1135 }
1136
1137 final protected function doQuickOperationsInternal( array $ops ) {
1138 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1139 $status = $this->newStatus();
1140
1141 // Fix up custom header name/value pairs...
1142 $ops = array_map( [ $this, 'sanitizeOpHeaders' ], $ops );
1143
1144 // Clear any file cache entries
1145 $this->clearCache();
1146
1147 $supportedOps = [ 'create', 'store', 'copy', 'move', 'delete', 'describe', 'null' ];
1148 // Parallel ops may be disabled in config due to dependencies (e.g. needing popen())
1149 $async = ( $this->parallelize === 'implicit' && count( $ops ) > 1 );
1150 $maxConcurrency = $this->concurrency; // throttle
1151 /** @var StatusValue[] $statuses */
1152 $statuses = []; // array of (index => StatusValue)
1153 $fileOpHandles = []; // list of (index => handle) arrays
1154 $curFileOpHandles = []; // current handle batch
1155 // Perform the sync-only ops and build up op handles for the async ops...
1156 foreach ( $ops as $index => $params ) {
1157 if ( !in_array( $params['op'], $supportedOps ) ) {
1158 throw new FileBackendError( "Operation '{$params['op']}' is not supported." );
1159 }
1160 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1161 $subStatus = $this->$method( [ 'async' => $async ] + $params );
1162 if ( $subStatus->value instanceof FileBackendStoreOpHandle ) { // async
1163 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1164 $fileOpHandles[] = $curFileOpHandles; // push this batch
1165 $curFileOpHandles = [];
1166 }
1167 $curFileOpHandles[$index] = $subStatus->value; // keep index
1168 } else { // error or completed
1169 $statuses[$index] = $subStatus; // keep index
1170 }
1171 }
1172 if ( count( $curFileOpHandles ) ) {
1173 $fileOpHandles[] = $curFileOpHandles; // last batch
1174 }
1175 // Do all the async ops that can be done concurrently...
1176 foreach ( $fileOpHandles as $fileHandleBatch ) {
1177 $statuses = $statuses + $this->executeOpHandlesInternal( $fileHandleBatch );
1178 }
1179 // Marshall and merge all the responses...
1180 foreach ( $statuses as $index => $subStatus ) {
1181 $status->merge( $subStatus );
1182 if ( $subStatus->isOK() ) {
1183 $status->success[$index] = true;
1184 ++$status->successCount;
1185 } else {
1186 $status->success[$index] = false;
1187 ++$status->failCount;
1188 }
1189 }
1190
1191 return $status;
1192 }
1193
1194 /**
1195 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1196 * The resulting StatusValue object fields will correspond
1197 * to the order in which the handles where given.
1198 *
1199 * @param FileBackendStoreOpHandle[] $fileOpHandles
1200 *
1201 * @throws FileBackendError
1202 * @return StatusValue[] Map of StatusValue objects
1203 */
1204 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1205 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1206
1207 foreach ( $fileOpHandles as $fileOpHandle ) {
1208 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle ) ) {
1209 throw new InvalidArgumentException( "Got a non-FileBackendStoreOpHandle object." );
1210 } elseif ( $fileOpHandle->backend->getName() !== $this->getName() ) {
1211 throw new InvalidArgumentException(
1212 "Got a FileBackendStoreOpHandle for the wrong backend." );
1213 }
1214 }
1215 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1216 foreach ( $fileOpHandles as $fileOpHandle ) {
1217 $fileOpHandle->closeResources();
1218 }
1219
1220 return $res;
1221 }
1222
1223 /**
1224 * @see FileBackendStore::executeOpHandlesInternal()
1225 *
1226 * @param FileBackendStoreOpHandle[] $fileOpHandles
1227 *
1228 * @throws FileBackendError
1229 * @return StatusValue[] List of corresponding StatusValue objects
1230 */
1231 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1232 if ( count( $fileOpHandles ) ) {
1233 throw new LogicException( "Backend does not support asynchronous operations." );
1234 }
1235
1236 return [];
1237 }
1238
1239 /**
1240 * Normalize and filter HTTP headers from a file operation
1241 *
1242 * This normalizes and strips long HTTP headers from a file operation.
1243 * Most headers are just numbers, but some are allowed to be long.
1244 * This function is useful for cleaning up headers and avoiding backend
1245 * specific errors, especially in the middle of batch file operations.
1246 *
1247 * @param array $op Same format as doOperation()
1248 * @return array
1249 */
1250 protected function sanitizeOpHeaders( array $op ) {
1251 static $longs = [ 'content-disposition' ];
1252
1253 if ( isset( $op['headers'] ) ) { // op sets HTTP headers
1254 $newHeaders = [];
1255 foreach ( $op['headers'] as $name => $value ) {
1256 $name = strtolower( $name );
1257 $maxHVLen = in_array( $name, $longs ) ? INF : 255;
1258 if ( strlen( $name ) > 255 || strlen( $value ) > $maxHVLen ) {
1259 trigger_error( "Header '$name: $value' is too long." );
1260 } else {
1261 $newHeaders[$name] = strlen( $value ) ? $value : ''; // null/false => ""
1262 }
1263 }
1264 $op['headers'] = $newHeaders;
1265 }
1266
1267 return $op;
1268 }
1269
1270 final public function preloadCache( array $paths ) {
1271 $fullConts = []; // full container names
1272 foreach ( $paths as $path ) {
1273 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1274 $fullConts[] = $fullCont;
1275 }
1276 // Load from the persistent file and container caches
1277 $this->primeContainerCache( $fullConts );
1278 $this->primeFileCache( $paths );
1279 }
1280
1281 final public function clearCache( array $paths = null ) {
1282 if ( is_array( $paths ) ) {
1283 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1284 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1285 }
1286 if ( $paths === null ) {
1287 $this->cheapCache->clear();
1288 $this->expensiveCache->clear();
1289 } else {
1290 foreach ( $paths as $path ) {
1291 $this->cheapCache->clear( $path );
1292 $this->expensiveCache->clear( $path );
1293 }
1294 }
1295 $this->doClearCache( $paths );
1296 }
1297
1298 /**
1299 * Clears any additional stat caches for storage paths
1300 *
1301 * @see FileBackend::clearCache()
1302 *
1303 * @param array $paths Storage paths (optional)
1304 */
1305 protected function doClearCache( array $paths = null ) {
1306 }
1307
1308 final public function preloadFileStat( array $params ) {
1309 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1310 $success = true; // no network errors
1311
1312 $params['concurrency'] = ( $this->parallelize !== 'off' ) ? $this->concurrency : 1;
1313 $stats = $this->doGetFileStatMulti( $params );
1314 if ( $stats === null ) {
1315 return true; // not supported
1316 }
1317
1318 $latest = !empty( $params['latest'] ); // use latest data?
1319 foreach ( $stats as $path => $stat ) {
1320 $path = FileBackend::normalizeStoragePath( $path );
1321 if ( $path === null ) {
1322 continue; // this shouldn't happen
1323 }
1324 if ( is_array( $stat ) ) { // file exists
1325 // Strongly consistent backends can automatically set "latest"
1326 $stat['latest'] = isset( $stat['latest'] ) ? $stat['latest'] : $latest;
1327 $this->cheapCache->set( $path, 'stat', $stat );
1328 $this->setFileCache( $path, $stat ); // update persistent cache
1329 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
1330 $this->cheapCache->set( $path, 'sha1',
1331 [ 'hash' => $stat['sha1'], 'latest' => $latest ] );
1332 }
1333 if ( isset( $stat['xattr'] ) ) { // some backends store headers/metadata
1334 $stat['xattr'] = self::normalizeXAttributes( $stat['xattr'] );
1335 $this->cheapCache->set( $path, 'xattr',
1336 [ 'map' => $stat['xattr'], 'latest' => $latest ] );
1337 }
1338 } elseif ( $stat === false ) { // file does not exist
1339 $this->cheapCache->set( $path, 'stat',
1340 $latest ? 'NOT_EXIST_LATEST' : 'NOT_EXIST' );
1341 $this->cheapCache->set( $path, 'xattr',
1342 [ 'map' => false, 'latest' => $latest ] );
1343 $this->cheapCache->set( $path, 'sha1',
1344 [ 'hash' => false, 'latest' => $latest ] );
1345 $this->logger->debug( __METHOD__ . ": File $path does not exist.\n" );
1346 } else { // an error occurred
1347 $success = false;
1348 $this->logger->warning( __METHOD__ . ": Could not stat file $path.\n" );
1349 }
1350 }
1351
1352 return $success;
1353 }
1354
1355 /**
1356 * Get file stat information (concurrently if possible) for several files
1357 *
1358 * @see FileBackend::getFileStat()
1359 *
1360 * @param array $params Parameters include:
1361 * - srcs : list of source storage paths
1362 * - latest : use the latest available data
1363 * @return array|null Map of storage paths to array|bool|null (returns null if not supported)
1364 * @since 1.23
1365 */
1366 protected function doGetFileStatMulti( array $params ) {
1367 return null; // not supported
1368 }
1369
1370 /**
1371 * Is this a key/value store where directories are just virtual?
1372 * Virtual directories exists in so much as files exists that are
1373 * prefixed with the directory path followed by a forward slash.
1374 *
1375 * @return bool
1376 */
1377 abstract protected function directoriesAreVirtual();
1378
1379 /**
1380 * Check if a short container name is valid
1381 *
1382 * This checks for length and illegal characters.
1383 * This may disallow certain characters that can appear
1384 * in the prefix used to make the full container name.
1385 *
1386 * @param string $container
1387 * @return bool
1388 */
1389 final protected static function isValidShortContainerName( $container ) {
1390 // Suffixes like '.xxx' (hex shard chars) or '.seg' (file segments)
1391 // might be used by subclasses. Reserve the dot character for sanity.
1392 // The only way dots end up in containers (e.g. resolveStoragePath)
1393 // is due to the wikiId container prefix or the above suffixes.
1394 return self::isValidContainerName( $container ) && !preg_match( '/[.]/', $container );
1395 }
1396
1397 /**
1398 * Check if a full container name is valid
1399 *
1400 * This checks for length and illegal characters.
1401 * Limiting the characters makes migrations to other stores easier.
1402 *
1403 * @param string $container
1404 * @return bool
1405 */
1406 final protected static function isValidContainerName( $container ) {
1407 // This accounts for NTFS, Swift, and Ceph restrictions
1408 // and disallows directory separators or traversal characters.
1409 // Note that matching strings URL encode to the same string;
1410 // in Swift/Ceph, the length restriction is *after* URL encoding.
1411 return (bool)preg_match( '/^[a-z0-9][a-z0-9-_.]{0,199}$/i', $container );
1412 }
1413
1414 /**
1415 * Splits a storage path into an internal container name,
1416 * an internal relative file name, and a container shard suffix.
1417 * Any shard suffix is already appended to the internal container name.
1418 * This also checks that the storage path is valid and within this backend.
1419 *
1420 * If the container is sharded but a suffix could not be determined,
1421 * this means that the path can only refer to a directory and can only
1422 * be scanned by looking in all the container shards.
1423 *
1424 * @param string $storagePath
1425 * @return array (container, path, container suffix) or (null, null, null) if invalid
1426 */
1427 final protected function resolveStoragePath( $storagePath ) {
1428 list( $backend, $shortCont, $relPath ) = self::splitStoragePath( $storagePath );
1429 if ( $backend === $this->name ) { // must be for this backend
1430 $relPath = self::normalizeContainerPath( $relPath );
1431 if ( $relPath !== null && self::isValidShortContainerName( $shortCont ) ) {
1432 // Get shard for the normalized path if this container is sharded
1433 $cShard = $this->getContainerShard( $shortCont, $relPath );
1434 // Validate and sanitize the relative path (backend-specific)
1435 $relPath = $this->resolveContainerPath( $shortCont, $relPath );
1436 if ( $relPath !== null ) {
1437 // Prepend any wiki ID prefix to the container name
1438 $container = $this->fullContainerName( $shortCont );
1439 if ( self::isValidContainerName( $container ) ) {
1440 // Validate and sanitize the container name (backend-specific)
1441 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1442 if ( $container !== null ) {
1443 return [ $container, $relPath, $cShard ];
1444 }
1445 }
1446 }
1447 }
1448 }
1449
1450 return [ null, null, null ];
1451 }
1452
1453 /**
1454 * Like resolveStoragePath() except null values are returned if
1455 * the container is sharded and the shard could not be determined
1456 * or if the path ends with '/'. The latter case is illegal for FS
1457 * backends and can confuse listings for object store backends.
1458 *
1459 * This function is used when resolving paths that must be valid
1460 * locations for files. Directory and listing functions should
1461 * generally just use resolveStoragePath() instead.
1462 *
1463 * @see FileBackendStore::resolveStoragePath()
1464 *
1465 * @param string $storagePath
1466 * @return array (container, path) or (null, null) if invalid
1467 */
1468 final protected function resolveStoragePathReal( $storagePath ) {
1469 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1470 if ( $cShard !== null && substr( $relPath, -1 ) !== '/' ) {
1471 return [ $container, $relPath ];
1472 }
1473
1474 return [ null, null ];
1475 }
1476
1477 /**
1478 * Get the container name shard suffix for a given path.
1479 * Any empty suffix means the container is not sharded.
1480 *
1481 * @param string $container Container name
1482 * @param string $relPath Storage path relative to the container
1483 * @return string|null Returns null if shard could not be determined
1484 */
1485 final protected function getContainerShard( $container, $relPath ) {
1486 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1487 if ( $levels == 1 || $levels == 2 ) {
1488 // Hash characters are either base 16 or 36
1489 $char = ( $base == 36 ) ? '[0-9a-z]' : '[0-9a-f]';
1490 // Get a regex that represents the shard portion of paths.
1491 // The concatenation of the captures gives us the shard.
1492 if ( $levels === 1 ) { // 16 or 36 shards per container
1493 $hashDirRegex = '(' . $char . ')';
1494 } else { // 256 or 1296 shards per container
1495 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1496 $hashDirRegex = $char . '/(' . $char . '{2})';
1497 } else { // short hash dir format (e.g. "a/b/c")
1498 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1499 }
1500 }
1501 // Allow certain directories to be above the hash dirs so as
1502 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1503 // They must be 2+ chars to avoid any hash directory ambiguity.
1504 $m = [];
1505 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1506 return '.' . implode( '', array_slice( $m, 1 ) );
1507 }
1508
1509 return null; // failed to match
1510 }
1511
1512 return ''; // no sharding
1513 }
1514
1515 /**
1516 * Check if a storage path maps to a single shard.
1517 * Container dirs like "a", where the container shards on "x/xy",
1518 * can reside on several shards. Such paths are tricky to handle.
1519 *
1520 * @param string $storagePath Storage path
1521 * @return bool
1522 */
1523 final public function isSingleShardPathInternal( $storagePath ) {
1524 list( , , $shard ) = $this->resolveStoragePath( $storagePath );
1525
1526 return ( $shard !== null );
1527 }
1528
1529 /**
1530 * Get the sharding config for a container.
1531 * If greater than 0, then all file storage paths within
1532 * the container are required to be hashed accordingly.
1533 *
1534 * @param string $container
1535 * @return array (integer levels, integer base, repeat flag) or (0, 0, false)
1536 */
1537 final protected function getContainerHashLevels( $container ) {
1538 if ( isset( $this->shardViaHashLevels[$container] ) ) {
1539 $config = $this->shardViaHashLevels[$container];
1540 $hashLevels = (int)$config['levels'];
1541 if ( $hashLevels == 1 || $hashLevels == 2 ) {
1542 $hashBase = (int)$config['base'];
1543 if ( $hashBase == 16 || $hashBase == 36 ) {
1544 return [ $hashLevels, $hashBase, $config['repeat'] ];
1545 }
1546 }
1547 }
1548
1549 return [ 0, 0, false ]; // no sharding
1550 }
1551
1552 /**
1553 * Get a list of full container shard suffixes for a container
1554 *
1555 * @param string $container
1556 * @return array
1557 */
1558 final protected function getContainerSuffixes( $container ) {
1559 $shards = [];
1560 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1561 if ( $digits > 0 ) {
1562 $numShards = pow( $base, $digits );
1563 for ( $index = 0; $index < $numShards; $index++ ) {
1564 $shards[] = '.' . Wikimedia\base_convert( $index, 10, $base, $digits );
1565 }
1566 }
1567
1568 return $shards;
1569 }
1570
1571 /**
1572 * Get the full container name, including the wiki ID prefix
1573 *
1574 * @param string $container
1575 * @return string
1576 */
1577 final protected function fullContainerName( $container ) {
1578 if ( $this->domainId != '' ) {
1579 return "{$this->domainId}-$container";
1580 } else {
1581 return $container;
1582 }
1583 }
1584
1585 /**
1586 * Resolve a container name, checking if it's allowed by the backend.
1587 * This is intended for internal use, such as encoding illegal chars.
1588 * Subclasses can override this to be more restrictive.
1589 *
1590 * @param string $container
1591 * @return string|null
1592 */
1593 protected function resolveContainerName( $container ) {
1594 return $container;
1595 }
1596
1597 /**
1598 * Resolve a relative storage path, checking if it's allowed by the backend.
1599 * This is intended for internal use, such as encoding illegal chars or perhaps
1600 * getting absolute paths (e.g. FS based backends). Note that the relative path
1601 * may be the empty string (e.g. the path is simply to the container).
1602 *
1603 * @param string $container Container name
1604 * @param string $relStoragePath Storage path relative to the container
1605 * @return string|null Path or null if not valid
1606 */
1607 protected function resolveContainerPath( $container, $relStoragePath ) {
1608 return $relStoragePath;
1609 }
1610
1611 /**
1612 * Get the cache key for a container
1613 *
1614 * @param string $container Resolved container name
1615 * @return string
1616 */
1617 private function containerCacheKey( $container ) {
1618 return "filebackend:{$this->name}:{$this->domainId}:container:{$container}";
1619 }
1620
1621 /**
1622 * Set the cached info for a container
1623 *
1624 * @param string $container Resolved container name
1625 * @param array $val Information to cache
1626 */
1627 final protected function setContainerCache( $container, array $val ) {
1628 $this->memCache->set( $this->containerCacheKey( $container ), $val, 14 * 86400 );
1629 }
1630
1631 /**
1632 * Delete the cached info for a container.
1633 * The cache key is salted for a while to prevent race conditions.
1634 *
1635 * @param string $container Resolved container name
1636 */
1637 final protected function deleteContainerCache( $container ) {
1638 if ( !$this->memCache->delete( $this->containerCacheKey( $container ), 300 ) ) {
1639 trigger_error( "Unable to delete stat cache for container $container." );
1640 }
1641 }
1642
1643 /**
1644 * Do a batch lookup from cache for container stats for all containers
1645 * used in a list of container names or storage paths objects.
1646 * This loads the persistent cache values into the process cache.
1647 *
1648 * @param array $items
1649 */
1650 final protected function primeContainerCache( array $items ) {
1651 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1652
1653 $paths = []; // list of storage paths
1654 $contNames = []; // (cache key => resolved container name)
1655 // Get all the paths/containers from the items...
1656 foreach ( $items as $item ) {
1657 if ( self::isStoragePath( $item ) ) {
1658 $paths[] = $item;
1659 } elseif ( is_string( $item ) ) { // full container name
1660 $contNames[$this->containerCacheKey( $item )] = $item;
1661 }
1662 }
1663 // Get all the corresponding cache keys for paths...
1664 foreach ( $paths as $path ) {
1665 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1666 if ( $fullCont !== null ) { // valid path for this backend
1667 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1668 }
1669 }
1670
1671 $contInfo = []; // (resolved container name => cache value)
1672 // Get all cache entries for these container cache keys...
1673 $values = $this->memCache->getMulti( array_keys( $contNames ) );
1674 foreach ( $values as $cacheKey => $val ) {
1675 $contInfo[$contNames[$cacheKey]] = $val;
1676 }
1677
1678 // Populate the container process cache for the backend...
1679 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1680 }
1681
1682 /**
1683 * Fill the backend-specific process cache given an array of
1684 * resolved container names and their corresponding cached info.
1685 * Only containers that actually exist should appear in the map.
1686 *
1687 * @param array $containerInfo Map of resolved container names to cached info
1688 */
1689 protected function doPrimeContainerCache( array $containerInfo ) {
1690 }
1691
1692 /**
1693 * Get the cache key for a file path
1694 *
1695 * @param string $path Normalized storage path
1696 * @return string
1697 */
1698 private function fileCacheKey( $path ) {
1699 return "filebackend:{$this->name}:{$this->domainId}:file:" . sha1( $path );
1700 }
1701
1702 /**
1703 * Set the cached stat info for a file path.
1704 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1705 * salting for the case when a file is created at a path were there was none before.
1706 *
1707 * @param string $path Storage path
1708 * @param array $val Stat information to cache
1709 */
1710 final protected function setFileCache( $path, array $val ) {
1711 $path = FileBackend::normalizeStoragePath( $path );
1712 if ( $path === null ) {
1713 return; // invalid storage path
1714 }
1715 $mtime = ConvertibleTimestamp::convert( TS_UNIX, $val['mtime'] );
1716 $ttl = $this->memCache->adaptiveTTL( $mtime, 7 * 86400, 300, .1 );
1717 $key = $this->fileCacheKey( $path );
1718 // Set the cache unless it is currently salted.
1719 $this->memCache->set( $key, $val, $ttl );
1720 }
1721
1722 /**
1723 * Delete the cached stat info for a file path.
1724 * The cache key is salted for a while to prevent race conditions.
1725 * Since negatives (404s) are not cached, this does not need to be called when
1726 * a file is created at a path were there was none before.
1727 *
1728 * @param string $path Storage path
1729 */
1730 final protected function deleteFileCache( $path ) {
1731 $path = FileBackend::normalizeStoragePath( $path );
1732 if ( $path === null ) {
1733 return; // invalid storage path
1734 }
1735 if ( !$this->memCache->delete( $this->fileCacheKey( $path ), 300 ) ) {
1736 trigger_error( "Unable to delete stat cache for file $path." );
1737 }
1738 }
1739
1740 /**
1741 * Do a batch lookup from cache for file stats for all paths
1742 * used in a list of storage paths or FileOp objects.
1743 * This loads the persistent cache values into the process cache.
1744 *
1745 * @param array $items List of storage paths
1746 */
1747 final protected function primeFileCache( array $items ) {
1748 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1749
1750 $paths = []; // list of storage paths
1751 $pathNames = []; // (cache key => storage path)
1752 // Get all the paths/containers from the items...
1753 foreach ( $items as $item ) {
1754 if ( self::isStoragePath( $item ) ) {
1755 $paths[] = FileBackend::normalizeStoragePath( $item );
1756 }
1757 }
1758 // Get rid of any paths that failed normalization...
1759 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1760 // Get all the corresponding cache keys for paths...
1761 foreach ( $paths as $path ) {
1762 list( , $rel, ) = $this->resolveStoragePath( $path );
1763 if ( $rel !== null ) { // valid path for this backend
1764 $pathNames[$this->fileCacheKey( $path )] = $path;
1765 }
1766 }
1767 // Get all cache entries for these file cache keys...
1768 $values = $this->memCache->getMulti( array_keys( $pathNames ) );
1769 foreach ( $values as $cacheKey => $val ) {
1770 $path = $pathNames[$cacheKey];
1771 if ( is_array( $val ) ) {
1772 $val['latest'] = false; // never completely trust cache
1773 $this->cheapCache->set( $path, 'stat', $val );
1774 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1775 $this->cheapCache->set( $path, 'sha1',
1776 [ 'hash' => $val['sha1'], 'latest' => false ] );
1777 }
1778 if ( isset( $val['xattr'] ) ) { // some backends store headers/metadata
1779 $val['xattr'] = self::normalizeXAttributes( $val['xattr'] );
1780 $this->cheapCache->set( $path, 'xattr',
1781 [ 'map' => $val['xattr'], 'latest' => false ] );
1782 }
1783 }
1784 }
1785 }
1786
1787 /**
1788 * Normalize file headers/metadata to the FileBackend::getFileXAttributes() format
1789 *
1790 * @param array $xattr
1791 * @return array
1792 * @since 1.22
1793 */
1794 final protected static function normalizeXAttributes( array $xattr ) {
1795 $newXAttr = [ 'headers' => [], 'metadata' => [] ];
1796
1797 foreach ( $xattr['headers'] as $name => $value ) {
1798 $newXAttr['headers'][strtolower( $name )] = $value;
1799 }
1800
1801 foreach ( $xattr['metadata'] as $name => $value ) {
1802 $newXAttr['metadata'][strtolower( $name )] = $value;
1803 }
1804
1805 return $newXAttr;
1806 }
1807
1808 /**
1809 * Set the 'concurrency' option from a list of operation options
1810 *
1811 * @param array $opts Map of operation options
1812 * @return array
1813 */
1814 final protected function setConcurrencyFlags( array $opts ) {
1815 $opts['concurrency'] = 1; // off
1816 if ( $this->parallelize === 'implicit' ) {
1817 if ( !isset( $opts['parallelize'] ) || $opts['parallelize'] ) {
1818 $opts['concurrency'] = $this->concurrency;
1819 }
1820 } elseif ( $this->parallelize === 'explicit' ) {
1821 if ( !empty( $opts['parallelize'] ) ) {
1822 $opts['concurrency'] = $this->concurrency;
1823 }
1824 }
1825
1826 return $opts;
1827 }
1828
1829 /**
1830 * Get the content type to use in HEAD/GET requests for a file
1831 *
1832 * @param string $storagePath
1833 * @param string|null $content File data
1834 * @param string|null $fsPath File system path
1835 * @return string MIME type
1836 */
1837 protected function getContentType( $storagePath, $content, $fsPath ) {
1838 if ( $this->mimeCallback ) {
1839 return call_user_func_array( $this->mimeCallback, func_get_args() );
1840 }
1841
1842 $mime = null;
1843 if ( $fsPath !== null && function_exists( 'finfo_file' ) ) {
1844 $finfo = finfo_open( FILEINFO_MIME_TYPE );
1845 $mime = finfo_file( $finfo, $fsPath );
1846 finfo_close( $finfo );
1847 }
1848
1849 return is_string( $mime ) ? $mime : 'unknown/unknown';
1850 }
1851 }
1852
1853 /**
1854 * FileBackendStore helper class for performing asynchronous file operations.
1855 *
1856 * For example, calling FileBackendStore::createInternal() with the "async"
1857 * param flag may result in a StatusValue that contains this object as a value.
1858 * This class is largely backend-specific and is mostly just "magic" to be
1859 * passed to FileBackendStore::executeOpHandlesInternal().
1860 */
1861 abstract class FileBackendStoreOpHandle {
1862 /** @var array */
1863 public $params = []; // params to caller functions
1864 /** @var FileBackendStore */
1865 public $backend;
1866 /** @var array */
1867 public $resourcesToClose = [];
1868
1869 public $call; // string; name that identifies the function called
1870
1871 /**
1872 * Close all open file handles
1873 */
1874 public function closeResources() {
1875 array_map( 'fclose', $this->resourcesToClose );
1876 }
1877 }
1878
1879 /**
1880 * FileBackendStore helper function to handle listings that span container shards.
1881 * Do not use this class from places outside of FileBackendStore.
1882 *
1883 * @ingroup FileBackend
1884 */
1885 abstract class FileBackendStoreShardListIterator extends FilterIterator {
1886 /** @var FileBackendStore */
1887 protected $backend;
1888
1889 /** @var array */
1890 protected $params;
1891
1892 /** @var string Full container name */
1893 protected $container;
1894
1895 /** @var string Resolved relative path */
1896 protected $directory;
1897
1898 /** @var array */
1899 protected $multiShardPaths = []; // (rel path => 1)
1900
1901 /**
1902 * @param FileBackendStore $backend
1903 * @param string $container Full storage container name
1904 * @param string $dir Storage directory relative to container
1905 * @param array $suffixes List of container shard suffixes
1906 * @param array $params
1907 */
1908 public function __construct(
1909 FileBackendStore $backend, $container, $dir, array $suffixes, array $params
1910 ) {
1911 $this->backend = $backend;
1912 $this->container = $container;
1913 $this->directory = $dir;
1914 $this->params = $params;
1915
1916 $iter = new AppendIterator();
1917 foreach ( $suffixes as $suffix ) {
1918 $iter->append( $this->listFromShard( $this->container . $suffix ) );
1919 }
1920
1921 parent::__construct( $iter );
1922 }
1923
1924 public function accept() {
1925 $rel = $this->getInnerIterator()->current(); // path relative to given directory
1926 $path = $this->params['dir'] . "/{$rel}"; // full storage path
1927 if ( $this->backend->isSingleShardPathInternal( $path ) ) {
1928 return true; // path is only on one shard; no issue with duplicates
1929 } elseif ( isset( $this->multiShardPaths[$rel] ) ) {
1930 // Don't keep listing paths that are on multiple shards
1931 return false;
1932 } else {
1933 $this->multiShardPaths[$rel] = 1;
1934
1935 return true;
1936 }
1937 }
1938
1939 public function rewind() {
1940 parent::rewind();
1941 $this->multiShardPaths = [];
1942 }
1943
1944 /**
1945 * Get the list for a given container shard
1946 *
1947 * @param string $container Resolved container name
1948 * @return Iterator
1949 */
1950 abstract protected function listFromShard( $container );
1951 }
1952
1953 /**
1954 * Iterator for listing directories
1955 */
1956 class FileBackendStoreShardDirIterator extends FileBackendStoreShardListIterator {
1957 protected function listFromShard( $container ) {
1958 $list = $this->backend->getDirectoryListInternal(
1959 $container, $this->directory, $this->params );
1960 if ( $list === null ) {
1961 return new ArrayIterator( [] );
1962 } else {
1963 return is_array( $list ) ? new ArrayIterator( $list ) : $list;
1964 }
1965 }
1966 }
1967
1968 /**
1969 * Iterator for listing regular files
1970 */
1971 class FileBackendStoreShardFileIterator extends FileBackendStoreShardListIterator {
1972 protected function listFromShard( $container ) {
1973 $list = $this->backend->getFileListInternal(
1974 $container, $this->directory, $this->params );
1975 if ( $list === null ) {
1976 return new ArrayIterator( [] );
1977 } else {
1978 return is_array( $list ) ? new ArrayIterator( $list ) : $list;
1979 }
1980 }
1981 }