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