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