Title: Title::getSubpage should not lose the interwiki prefix
[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 we want the latest data, check that this cached
648 // value was in fact fetched with the latest available data.
649 if ( is_array( $stat ) ) {
650 if (
651 ( !$latest || $stat['latest'] ) &&
652 ( !$requireSHA1 || isset( $stat['sha1'] ) )
653 ) {
654 return $stat;
655 }
656 } elseif ( in_array( $stat, [ 'NOT_EXIST', 'NOT_EXIST_LATEST' ], true ) ) {
657 if ( !$latest || $stat === 'NOT_EXIST_LATEST' ) {
658 return false;
659 }
660 }
661
662 $stat = $this->doGetFileStat( $params );
663
664 if ( is_array( $stat ) ) { // file exists
665 // Strongly consistent backends can automatically set "latest"
666 $stat['latest'] = $stat['latest'] ?? $latest;
667 $this->cheapCache->setField( $path, 'stat', $stat );
668 $this->setFileCache( $path, $stat ); // update persistent cache
669 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
670 $this->cheapCache->setField( $path, 'sha1',
671 [ 'hash' => $stat['sha1'], 'latest' => $latest ] );
672 }
673 if ( isset( $stat['xattr'] ) ) { // some backends store headers/metadata
674 $stat['xattr'] = self::normalizeXAttributes( $stat['xattr'] );
675 $this->cheapCache->setField( $path, 'xattr',
676 [ 'map' => $stat['xattr'], 'latest' => $latest ] );
677 }
678 } elseif ( $stat === false ) { // file does not exist
679 $this->cheapCache->setField( $path, 'stat', $latest ? 'NOT_EXIST_LATEST' : 'NOT_EXIST' );
680 $this->cheapCache->setField( $path, 'xattr', [ 'map' => false, 'latest' => $latest ] );
681 $this->cheapCache->setField( $path, 'sha1', [ 'hash' => false, 'latest' => $latest ] );
682 $this->logger->debug( __METHOD__ . ': File {path} does not exist', [
683 'path' => $path,
684 ] );
685 } else { // an error occurred
686 $this->logger->warning( __METHOD__ . ': Could not stat file {path}', [
687 'path' => $path,
688 ] );
689 }
690
691 return $stat;
692 }
693
694 /**
695 * @see FileBackendStore::getFileStat()
696 * @param array $params
697 */
698 abstract protected function doGetFileStat( array $params );
699
700 public function getFileContentsMulti( array $params ) {
701 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
702
703 $params = $this->setConcurrencyFlags( $params );
704 $contents = $this->doGetFileContentsMulti( $params );
705
706 return $contents;
707 }
708
709 /**
710 * @see FileBackendStore::getFileContentsMulti()
711 * @param array $params
712 * @return array
713 */
714 protected function doGetFileContentsMulti( array $params ) {
715 $contents = [];
716 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
717 Wikimedia\suppressWarnings();
718 $contents[$path] = $fsFile ? file_get_contents( $fsFile->getPath() ) : false;
719 Wikimedia\restoreWarnings();
720 }
721
722 return $contents;
723 }
724
725 final public function getFileXAttributes( array $params ) {
726 $path = self::normalizeStoragePath( $params['src'] );
727 if ( $path === null ) {
728 return false; // invalid storage path
729 }
730 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
731 $latest = !empty( $params['latest'] ); // use latest data?
732 if ( $this->cheapCache->hasField( $path, 'xattr', self::CACHE_TTL ) ) {
733 $stat = $this->cheapCache->getField( $path, 'xattr' );
734 // If we want the latest data, check that this cached
735 // value was in fact fetched with the latest available data.
736 if ( !$latest || $stat['latest'] ) {
737 return $stat['map'];
738 }
739 }
740 $fields = $this->doGetFileXAttributes( $params );
741 $fields = is_array( $fields ) ? self::normalizeXAttributes( $fields ) : false;
742 $this->cheapCache->setField( $path, 'xattr', [ 'map' => $fields, 'latest' => $latest ] );
743
744 return $fields;
745 }
746
747 /**
748 * @see FileBackendStore::getFileXAttributes()
749 * @param array $params
750 * @return array[][]
751 */
752 protected function doGetFileXAttributes( array $params ) {
753 return [ 'headers' => [], 'metadata' => [] ]; // not supported
754 }
755
756 final public function getFileSha1Base36( array $params ) {
757 $path = self::normalizeStoragePath( $params['src'] );
758 if ( $path === null ) {
759 return false; // invalid storage path
760 }
761 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
762 $latest = !empty( $params['latest'] ); // use latest data?
763 if ( $this->cheapCache->hasField( $path, 'sha1', self::CACHE_TTL ) ) {
764 $stat = $this->cheapCache->getField( $path, 'sha1' );
765 // If we want the latest data, check that this cached
766 // value was in fact fetched with the latest available data.
767 if ( !$latest || $stat['latest'] ) {
768 return $stat['hash'];
769 }
770 }
771 $hash = $this->doGetFileSha1Base36( $params );
772 $this->cheapCache->setField( $path, 'sha1', [ 'hash' => $hash, 'latest' => $latest ] );
773
774 return $hash;
775 }
776
777 /**
778 * @see FileBackendStore::getFileSha1Base36()
779 * @param array $params
780 * @return bool|string
781 */
782 protected function doGetFileSha1Base36( array $params ) {
783 $fsFile = $this->getLocalReference( $params );
784 if ( !$fsFile ) {
785 return false;
786 } else {
787 return $fsFile->getSha1Base36();
788 }
789 }
790
791 final public function getFileProps( array $params ) {
792 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
793 $fsFile = $this->getLocalReference( $params );
794 $props = $fsFile ? $fsFile->getProps() : FSFile::placeholderProps();
795
796 return $props;
797 }
798
799 final public function getLocalReferenceMulti( array $params ) {
800 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
801
802 $params = $this->setConcurrencyFlags( $params );
803
804 $fsFiles = []; // (path => FSFile)
805 $latest = !empty( $params['latest'] ); // use latest data?
806 // Reuse any files already in process cache...
807 foreach ( $params['srcs'] as $src ) {
808 $path = self::normalizeStoragePath( $src );
809 if ( $path === null ) {
810 $fsFiles[$src] = null; // invalid storage path
811 } elseif ( $this->expensiveCache->hasField( $path, 'localRef' ) ) {
812 $val = $this->expensiveCache->getField( $path, 'localRef' );
813 // If we want the latest data, check that this cached
814 // value was in fact fetched with the latest available data.
815 if ( !$latest || $val['latest'] ) {
816 $fsFiles[$src] = $val['object'];
817 }
818 }
819 }
820 // Fetch local references of any remaning files...
821 $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
822 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
823 $fsFiles[$path] = $fsFile;
824 if ( $fsFile ) { // update the process cache...
825 $this->expensiveCache->setField( $path, 'localRef',
826 [ 'object' => $fsFile, 'latest' => $latest ] );
827 }
828 }
829
830 return $fsFiles;
831 }
832
833 /**
834 * @see FileBackendStore::getLocalReferenceMulti()
835 * @param array $params
836 * @return array
837 */
838 protected function doGetLocalReferenceMulti( array $params ) {
839 return $this->doGetLocalCopyMulti( $params );
840 }
841
842 final public function getLocalCopyMulti( array $params ) {
843 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
844
845 $params = $this->setConcurrencyFlags( $params );
846 $tmpFiles = $this->doGetLocalCopyMulti( $params );
847
848 return $tmpFiles;
849 }
850
851 /**
852 * @see FileBackendStore::getLocalCopyMulti()
853 * @param array $params
854 * @return array
855 */
856 abstract protected function doGetLocalCopyMulti( array $params );
857
858 /**
859 * @see FileBackend::getFileHttpUrl()
860 * @param array $params
861 * @return string|null
862 */
863 public function getFileHttpUrl( array $params ) {
864 return null; // not supported
865 }
866
867 final public function streamFile( array $params ) {
868 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
869 $status = $this->newStatus();
870
871 // Always set some fields for subclass convenience
872 $params['options'] = $params['options'] ?? [];
873 $params['headers'] = $params['headers'] ?? [];
874
875 // Don't stream it out as text/html if there was a PHP error
876 if ( ( empty( $params['headless'] ) || $params['headers'] ) && headers_sent() ) {
877 print "Headers already sent, terminating.\n";
878 $status->fatal( 'backend-fail-stream', $params['src'] );
879 return $status;
880 }
881
882 $status->merge( $this->doStreamFile( $params ) );
883
884 return $status;
885 }
886
887 /**
888 * @see FileBackendStore::streamFile()
889 * @param array $params
890 * @return StatusValue
891 */
892 protected function doStreamFile( array $params ) {
893 $status = $this->newStatus();
894
895 $flags = 0;
896 $flags |= !empty( $params['headless'] ) ? HTTPFileStreamer::STREAM_HEADLESS : 0;
897 $flags |= !empty( $params['allowOB'] ) ? HTTPFileStreamer::STREAM_ALLOW_OB : 0;
898
899 $fsFile = $this->getLocalReference( $params );
900 if ( $fsFile ) {
901 $streamer = new HTTPFileStreamer(
902 $fsFile->getPath(),
903 [
904 'obResetFunc' => $this->obResetFunc,
905 'streamMimeFunc' => $this->streamMimeFunc
906 ]
907 );
908 $res = $streamer->stream( $params['headers'], true, $params['options'], $flags );
909 } else {
910 $res = false;
911 HTTPFileStreamer::send404Message( $params['src'], $flags );
912 }
913
914 if ( !$res ) {
915 $status->fatal( 'backend-fail-stream', $params['src'] );
916 }
917
918 return $status;
919 }
920
921 final public function directoryExists( array $params ) {
922 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
923 if ( $dir === null ) {
924 return false; // invalid storage path
925 }
926 if ( $shard !== null ) { // confined to a single container/shard
927 return $this->doDirectoryExists( $fullCont, $dir, $params );
928 } else { // directory is on several shards
929 $this->logger->debug( __METHOD__ . ": iterating over all container shards.\n" );
930 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
931 $res = false; // response
932 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
933 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
934 if ( $exists ) {
935 $res = true;
936 break; // found one!
937 } elseif ( $exists === null ) { // error?
938 $res = null; // if we don't find anything, it is indeterminate
939 }
940 }
941
942 return $res;
943 }
944 }
945
946 /**
947 * @see FileBackendStore::directoryExists()
948 *
949 * @param string $container Resolved container name
950 * @param string $dir Resolved path relative to container
951 * @param array $params
952 * @return bool|null
953 */
954 abstract protected function doDirectoryExists( $container, $dir, array $params );
955
956 final public function getDirectoryList( array $params ) {
957 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
958 if ( $dir === null ) { // invalid storage path
959 return null;
960 }
961 if ( $shard !== null ) {
962 // File listing is confined to a single container/shard
963 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
964 } else {
965 $this->logger->debug( __METHOD__ . ": iterating over all container shards.\n" );
966 // File listing spans multiple containers/shards
967 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
968
969 return new FileBackendStoreShardDirIterator( $this,
970 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
971 }
972 }
973
974 /**
975 * Do not call this function from places outside FileBackend
976 *
977 * @see FileBackendStore::getDirectoryList()
978 *
979 * @param string $container Resolved container name
980 * @param string $dir Resolved path relative to container
981 * @param array $params
982 * @return Traversable|array|null Returns null on failure
983 */
984 abstract public function getDirectoryListInternal( $container, $dir, array $params );
985
986 final public function getFileList( array $params ) {
987 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
988 if ( $dir === null ) { // invalid storage path
989 return null;
990 }
991 if ( $shard !== null ) {
992 // File listing is confined to a single container/shard
993 return $this->getFileListInternal( $fullCont, $dir, $params );
994 } else {
995 $this->logger->debug( __METHOD__ . ": iterating over all container shards.\n" );
996 // File listing spans multiple containers/shards
997 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
998
999 return new FileBackendStoreShardFileIterator( $this,
1000 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
1001 }
1002 }
1003
1004 /**
1005 * Do not call this function from places outside FileBackend
1006 *
1007 * @see FileBackendStore::getFileList()
1008 *
1009 * @param string $container Resolved container name
1010 * @param string $dir Resolved path relative to container
1011 * @param array $params
1012 * @return Traversable|string[]|null Returns null on failure
1013 */
1014 abstract public function getFileListInternal( $container, $dir, array $params );
1015
1016 /**
1017 * Return a list of FileOp objects from a list of operations.
1018 * Do not call this function from places outside FileBackend.
1019 *
1020 * The result must have the same number of items as the input.
1021 * An exception is thrown if an unsupported operation is requested.
1022 *
1023 * @param array $ops Same format as doOperations()
1024 * @return FileOp[] List of FileOp objects
1025 * @throws FileBackendError
1026 */
1027 final public function getOperationsInternal( array $ops ) {
1028 $supportedOps = [
1029 'store' => StoreFileOp::class,
1030 'copy' => CopyFileOp::class,
1031 'move' => MoveFileOp::class,
1032 'delete' => DeleteFileOp::class,
1033 'create' => CreateFileOp::class,
1034 'describe' => DescribeFileOp::class,
1035 'null' => NullFileOp::class
1036 ];
1037
1038 $performOps = []; // array of FileOp objects
1039 // Build up ordered array of FileOps...
1040 foreach ( $ops as $operation ) {
1041 $opName = $operation['op'];
1042 if ( isset( $supportedOps[$opName] ) ) {
1043 $class = $supportedOps[$opName];
1044 // Get params for this operation
1045 $params = $operation;
1046 // Append the FileOp class
1047 $performOps[] = new $class( $this, $params, $this->logger );
1048 } else {
1049 throw new FileBackendError( "Operation '$opName' is not supported." );
1050 }
1051 }
1052
1053 return $performOps;
1054 }
1055
1056 /**
1057 * Get a list of storage paths to lock for a list of operations
1058 * Returns an array with LockManager::LOCK_UW (shared locks) and
1059 * LockManager::LOCK_EX (exclusive locks) keys, each corresponding
1060 * to a list of storage paths to be locked. All returned paths are
1061 * normalized.
1062 *
1063 * @param array $performOps List of FileOp objects
1064 * @return array (LockManager::LOCK_UW => path list, LockManager::LOCK_EX => path list)
1065 */
1066 final public function getPathsToLockForOpsInternal( array $performOps ) {
1067 // Build up a list of files to lock...
1068 $paths = [ 'sh' => [], 'ex' => [] ];
1069 foreach ( $performOps as $fileOp ) {
1070 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1071 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1072 }
1073 // Optimization: if doing an EX lock anyway, don't also set an SH one
1074 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1075 // Get a shared lock on the parent directory of each path changed
1076 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1077
1078 return [
1079 LockManager::LOCK_UW => $paths['sh'],
1080 LockManager::LOCK_EX => $paths['ex']
1081 ];
1082 }
1083
1084 public function getScopedLocksForOps( array $ops, StatusValue $status ) {
1085 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1086
1087 return $this->getScopedFileLocks( $paths, 'mixed', $status );
1088 }
1089
1090 final protected function doOperationsInternal( array $ops, array $opts ) {
1091 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1092 $status = $this->newStatus();
1093
1094 // Fix up custom header name/value pairs...
1095 $ops = array_map( [ $this, 'sanitizeOpHeaders' ], $ops );
1096
1097 // Build up a list of FileOps...
1098 $performOps = $this->getOperationsInternal( $ops );
1099
1100 // Acquire any locks as needed...
1101 if ( empty( $opts['nonLocking'] ) ) {
1102 // Build up a list of files to lock...
1103 $paths = $this->getPathsToLockForOpsInternal( $performOps );
1104 // Try to lock those files for the scope of this function...
1105
1106 $scopeLock = $this->getScopedFileLocks( $paths, 'mixed', $status );
1107 if ( !$status->isOK() ) {
1108 return $status; // abort
1109 }
1110 }
1111
1112 // Clear any file cache entries (after locks acquired)
1113 if ( empty( $opts['preserveCache'] ) ) {
1114 $this->clearCache();
1115 }
1116
1117 // Build the list of paths involved
1118 $paths = [];
1119 foreach ( $performOps as $performOp ) {
1120 $paths = array_merge( $paths, $performOp->storagePathsRead() );
1121 $paths = array_merge( $paths, $performOp->storagePathsChanged() );
1122 }
1123
1124 // Enlarge the cache to fit the stat entries of these files
1125 $this->cheapCache->setMaxSize( max( 2 * count( $paths ), self::CACHE_CHEAP_SIZE ) );
1126
1127 // Load from the persistent container caches
1128 $this->primeContainerCache( $paths );
1129 // Get the latest stat info for all the files (having locked them)
1130 $ok = $this->preloadFileStat( [ 'srcs' => $paths, 'latest' => true ] );
1131
1132 if ( $ok ) {
1133 // Actually attempt the operation batch...
1134 $opts = $this->setConcurrencyFlags( $opts );
1135 $subStatus = FileOpBatch::attempt( $performOps, $opts, $this->fileJournal );
1136 } else {
1137 // If we could not even stat some files, then bail out...
1138 $subStatus = $this->newStatus( 'backend-fail-internal', $this->name );
1139 foreach ( $ops as $i => $op ) { // mark each op as failed
1140 $subStatus->success[$i] = false;
1141 ++$subStatus->failCount;
1142 }
1143 $this->logger->error( static::class . "-{$this->name} " .
1144 " stat failure; aborted operations: " . FormatJson::encode( $ops ) );
1145 }
1146
1147 // Merge errors into StatusValue fields
1148 $status->merge( $subStatus );
1149 $status->success = $subStatus->success; // not done in merge()
1150
1151 // Shrink the stat cache back to normal size
1152 $this->cheapCache->setMaxSize( self::CACHE_CHEAP_SIZE );
1153
1154 return $status;
1155 }
1156
1157 final protected function doQuickOperationsInternal( array $ops ) {
1158 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1159 $status = $this->newStatus();
1160
1161 // Fix up custom header name/value pairs...
1162 $ops = array_map( [ $this, 'sanitizeOpHeaders' ], $ops );
1163
1164 // Clear any file cache entries
1165 $this->clearCache();
1166
1167 $supportedOps = [ 'create', 'store', 'copy', 'move', 'delete', 'describe', 'null' ];
1168 // Parallel ops may be disabled in config due to dependencies (e.g. needing popen())
1169 $async = ( $this->parallelize === 'implicit' && count( $ops ) > 1 );
1170 $maxConcurrency = $this->concurrency; // throttle
1171 /** @var StatusValue[] $statuses */
1172 $statuses = []; // array of (index => StatusValue)
1173 $fileOpHandles = []; // list of (index => handle) arrays
1174 $curFileOpHandles = []; // current handle batch
1175 // Perform the sync-only ops and build up op handles for the async ops...
1176 foreach ( $ops as $index => $params ) {
1177 if ( !in_array( $params['op'], $supportedOps ) ) {
1178 throw new FileBackendError( "Operation '{$params['op']}' is not supported." );
1179 }
1180 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1181 $subStatus = $this->$method( [ 'async' => $async ] + $params );
1182 if ( $subStatus->value instanceof FileBackendStoreOpHandle ) { // async
1183 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1184 $fileOpHandles[] = $curFileOpHandles; // push this batch
1185 $curFileOpHandles = [];
1186 }
1187 $curFileOpHandles[$index] = $subStatus->value; // keep index
1188 } else { // error or completed
1189 $statuses[$index] = $subStatus; // keep index
1190 }
1191 }
1192 if ( count( $curFileOpHandles ) ) {
1193 $fileOpHandles[] = $curFileOpHandles; // last batch
1194 }
1195 // Do all the async ops that can be done concurrently...
1196 foreach ( $fileOpHandles as $fileHandleBatch ) {
1197 $statuses = $statuses + $this->executeOpHandlesInternal( $fileHandleBatch );
1198 }
1199 // Marshall and merge all the responses...
1200 foreach ( $statuses as $index => $subStatus ) {
1201 $status->merge( $subStatus );
1202 if ( $subStatus->isOK() ) {
1203 $status->success[$index] = true;
1204 ++$status->successCount;
1205 } else {
1206 $status->success[$index] = false;
1207 ++$status->failCount;
1208 }
1209 }
1210
1211 return $status;
1212 }
1213
1214 /**
1215 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1216 * The resulting StatusValue object fields will correspond
1217 * to the order in which the handles where given.
1218 *
1219 * @param FileBackendStoreOpHandle[] $fileOpHandles
1220 * @return StatusValue[] Map of StatusValue objects
1221 * @throws FileBackendError
1222 */
1223 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1224 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1225
1226 foreach ( $fileOpHandles as $fileOpHandle ) {
1227 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle ) ) {
1228 throw new InvalidArgumentException( "Expected FileBackendStoreOpHandle object." );
1229 } elseif ( $fileOpHandle->backend->getName() !== $this->getName() ) {
1230 throw new InvalidArgumentException( "Expected handle for this file backend." );
1231 }
1232 }
1233
1234 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1235 foreach ( $fileOpHandles as $fileOpHandle ) {
1236 $fileOpHandle->closeResources();
1237 }
1238
1239 return $res;
1240 }
1241
1242 /**
1243 * @see FileBackendStore::executeOpHandlesInternal()
1244 *
1245 * @param FileBackendStoreOpHandle[] $fileOpHandles
1246 *
1247 * @throws FileBackendError
1248 * @return StatusValue[] List of corresponding StatusValue objects
1249 */
1250 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1251 if ( count( $fileOpHandles ) ) {
1252 throw new LogicException( "Backend does not support asynchronous operations." );
1253 }
1254
1255 return [];
1256 }
1257
1258 /**
1259 * Normalize and filter HTTP headers from a file operation
1260 *
1261 * This normalizes and strips long HTTP headers from a file operation.
1262 * Most headers are just numbers, but some are allowed to be long.
1263 * This function is useful for cleaning up headers and avoiding backend
1264 * specific errors, especially in the middle of batch file operations.
1265 *
1266 * @param array $op Same format as doOperation()
1267 * @return array
1268 */
1269 protected function sanitizeOpHeaders( array $op ) {
1270 static $longs = [ 'content-disposition' ];
1271
1272 if ( isset( $op['headers'] ) ) { // op sets HTTP headers
1273 $newHeaders = [];
1274 foreach ( $op['headers'] as $name => $value ) {
1275 $name = strtolower( $name );
1276 $maxHVLen = in_array( $name, $longs ) ? INF : 255;
1277 if ( strlen( $name ) > 255 || strlen( $value ) > $maxHVLen ) {
1278 trigger_error( "Header '$name: $value' is too long." );
1279 } else {
1280 $newHeaders[$name] = strlen( $value ) ? $value : ''; // null/false => ""
1281 }
1282 }
1283 $op['headers'] = $newHeaders;
1284 }
1285
1286 return $op;
1287 }
1288
1289 final public function preloadCache( array $paths ) {
1290 $fullConts = []; // full container names
1291 foreach ( $paths as $path ) {
1292 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1293 $fullConts[] = $fullCont;
1294 }
1295 // Load from the persistent file and container caches
1296 $this->primeContainerCache( $fullConts );
1297 $this->primeFileCache( $paths );
1298 }
1299
1300 final public function clearCache( array $paths = null ) {
1301 if ( is_array( $paths ) ) {
1302 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1303 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1304 }
1305 if ( $paths === null ) {
1306 $this->cheapCache->clear();
1307 $this->expensiveCache->clear();
1308 } else {
1309 foreach ( $paths as $path ) {
1310 $this->cheapCache->clear( $path );
1311 $this->expensiveCache->clear( $path );
1312 }
1313 }
1314 $this->doClearCache( $paths );
1315 }
1316
1317 /**
1318 * Clears any additional stat caches for storage paths
1319 *
1320 * @see FileBackend::clearCache()
1321 *
1322 * @param array|null $paths Storage paths (optional)
1323 */
1324 protected function doClearCache( array $paths = null ) {
1325 }
1326
1327 final public function preloadFileStat( array $params ) {
1328 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1329 $success = true; // no network errors
1330
1331 $params['concurrency'] = ( $this->parallelize !== 'off' ) ? $this->concurrency : 1;
1332 $stats = $this->doGetFileStatMulti( $params );
1333 if ( $stats === null ) {
1334 return true; // not supported
1335 }
1336
1337 $latest = !empty( $params['latest'] ); // use latest data?
1338 foreach ( $stats as $path => $stat ) {
1339 $path = FileBackend::normalizeStoragePath( $path );
1340 if ( $path === null ) {
1341 continue; // this shouldn't happen
1342 }
1343 if ( is_array( $stat ) ) { // file exists
1344 // Strongly consistent backends can automatically set "latest"
1345 $stat['latest'] = $stat['latest'] ?? $latest;
1346 $this->cheapCache->setField( $path, 'stat', $stat );
1347 $this->setFileCache( $path, $stat ); // update persistent cache
1348 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
1349 $this->cheapCache->setField( $path, 'sha1',
1350 [ 'hash' => $stat['sha1'], 'latest' => $latest ] );
1351 }
1352 if ( isset( $stat['xattr'] ) ) { // some backends store headers/metadata
1353 $stat['xattr'] = self::normalizeXAttributes( $stat['xattr'] );
1354 $this->cheapCache->setField( $path, 'xattr',
1355 [ 'map' => $stat['xattr'], 'latest' => $latest ] );
1356 }
1357 } elseif ( $stat === false ) { // file does not exist
1358 $this->cheapCache->setField( $path, 'stat',
1359 $latest ? 'NOT_EXIST_LATEST' : 'NOT_EXIST' );
1360 $this->cheapCache->setField( $path, 'xattr',
1361 [ 'map' => false, 'latest' => $latest ] );
1362 $this->cheapCache->setField( $path, 'sha1',
1363 [ 'hash' => false, 'latest' => $latest ] );
1364 $this->logger->debug( __METHOD__ . ': File {path} does not exist', [
1365 'path' => $path,
1366 ] );
1367 } else { // an error occurred
1368 $success = false;
1369 $this->logger->warning( __METHOD__ . ': Could not stat file {path}', [
1370 'path' => $path,
1371 ] );
1372 }
1373 }
1374
1375 return $success;
1376 }
1377
1378 /**
1379 * Get file stat information (concurrently if possible) for several files
1380 *
1381 * @see FileBackend::getFileStat()
1382 *
1383 * @param array $params Parameters include:
1384 * - srcs : list of source storage paths
1385 * - latest : use the latest available data
1386 * @return array|null Map of storage paths to array|bool|null (returns null if not supported)
1387 * @since 1.23
1388 */
1389 protected function doGetFileStatMulti( array $params ) {
1390 return null; // not supported
1391 }
1392
1393 /**
1394 * Is this a key/value store where directories are just virtual?
1395 * Virtual directories exists in so much as files exists that are
1396 * prefixed with the directory path followed by a forward slash.
1397 *
1398 * @return bool
1399 */
1400 abstract protected function directoriesAreVirtual();
1401
1402 /**
1403 * Check if a short container name is valid
1404 *
1405 * This checks for length and illegal characters.
1406 * This may disallow certain characters that can appear
1407 * in the prefix used to make the full container name.
1408 *
1409 * @param string $container
1410 * @return bool
1411 */
1412 final protected static function isValidShortContainerName( $container ) {
1413 // Suffixes like '.xxx' (hex shard chars) or '.seg' (file segments)
1414 // might be used by subclasses. Reserve the dot character for sanity.
1415 // The only way dots end up in containers (e.g. resolveStoragePath)
1416 // is due to the wikiId container prefix or the above suffixes.
1417 return self::isValidContainerName( $container ) && !preg_match( '/[.]/', $container );
1418 }
1419
1420 /**
1421 * Check if a full container name is valid
1422 *
1423 * This checks for length and illegal characters.
1424 * Limiting the characters makes migrations to other stores easier.
1425 *
1426 * @param string $container
1427 * @return bool
1428 */
1429 final protected static function isValidContainerName( $container ) {
1430 // This accounts for NTFS, Swift, and Ceph restrictions
1431 // and disallows directory separators or traversal characters.
1432 // Note that matching strings URL encode to the same string;
1433 // in Swift/Ceph, the length restriction is *after* URL encoding.
1434 return (bool)preg_match( '/^[a-z0-9][a-z0-9-_.]{0,199}$/i', $container );
1435 }
1436
1437 /**
1438 * Splits a storage path into an internal container name,
1439 * an internal relative file name, and a container shard suffix.
1440 * Any shard suffix is already appended to the internal container name.
1441 * This also checks that the storage path is valid and within this backend.
1442 *
1443 * If the container is sharded but a suffix could not be determined,
1444 * this means that the path can only refer to a directory and can only
1445 * be scanned by looking in all the container shards.
1446 *
1447 * @param string $storagePath
1448 * @return array (container, path, container suffix) or (null, null, null) if invalid
1449 */
1450 final protected function resolveStoragePath( $storagePath ) {
1451 list( $backend, $shortCont, $relPath ) = self::splitStoragePath( $storagePath );
1452 if ( $backend === $this->name ) { // must be for this backend
1453 $relPath = self::normalizeContainerPath( $relPath );
1454 if ( $relPath !== null && self::isValidShortContainerName( $shortCont ) ) {
1455 // Get shard for the normalized path if this container is sharded
1456 $cShard = $this->getContainerShard( $shortCont, $relPath );
1457 // Validate and sanitize the relative path (backend-specific)
1458 $relPath = $this->resolveContainerPath( $shortCont, $relPath );
1459 if ( $relPath !== null ) {
1460 // Prepend any wiki ID prefix to the container name
1461 $container = $this->fullContainerName( $shortCont );
1462 if ( self::isValidContainerName( $container ) ) {
1463 // Validate and sanitize the container name (backend-specific)
1464 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1465 if ( $container !== null ) {
1466 return [ $container, $relPath, $cShard ];
1467 }
1468 }
1469 }
1470 }
1471 }
1472
1473 return [ null, null, null ];
1474 }
1475
1476 /**
1477 * Like resolveStoragePath() except null values are returned if
1478 * the container is sharded and the shard could not be determined
1479 * or if the path ends with '/'. The latter case is illegal for FS
1480 * backends and can confuse listings for object store backends.
1481 *
1482 * This function is used when resolving paths that must be valid
1483 * locations for files. Directory and listing functions should
1484 * generally just use resolveStoragePath() instead.
1485 *
1486 * @see FileBackendStore::resolveStoragePath()
1487 *
1488 * @param string $storagePath
1489 * @return array (container, path) or (null, null) if invalid
1490 */
1491 final protected function resolveStoragePathReal( $storagePath ) {
1492 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1493 if ( $cShard !== null && substr( $relPath, -1 ) !== '/' ) {
1494 return [ $container, $relPath ];
1495 }
1496
1497 return [ null, null ];
1498 }
1499
1500 /**
1501 * Get the container name shard suffix for a given path.
1502 * Any empty suffix means the container is not sharded.
1503 *
1504 * @param string $container Container name
1505 * @param string $relPath Storage path relative to the container
1506 * @return string|null Returns null if shard could not be determined
1507 */
1508 final protected function getContainerShard( $container, $relPath ) {
1509 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1510 if ( $levels == 1 || $levels == 2 ) {
1511 // Hash characters are either base 16 or 36
1512 $char = ( $base == 36 ) ? '[0-9a-z]' : '[0-9a-f]';
1513 // Get a regex that represents the shard portion of paths.
1514 // The concatenation of the captures gives us the shard.
1515 if ( $levels === 1 ) { // 16 or 36 shards per container
1516 $hashDirRegex = '(' . $char . ')';
1517 } else { // 256 or 1296 shards per container
1518 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1519 $hashDirRegex = $char . '/(' . $char . '{2})';
1520 } else { // short hash dir format (e.g. "a/b/c")
1521 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1522 }
1523 }
1524 // Allow certain directories to be above the hash dirs so as
1525 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1526 // They must be 2+ chars to avoid any hash directory ambiguity.
1527 $m = [];
1528 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1529 return '.' . implode( '', array_slice( $m, 1 ) );
1530 }
1531
1532 return null; // failed to match
1533 }
1534
1535 return ''; // no sharding
1536 }
1537
1538 /**
1539 * Check if a storage path maps to a single shard.
1540 * Container dirs like "a", where the container shards on "x/xy",
1541 * can reside on several shards. Such paths are tricky to handle.
1542 *
1543 * @param string $storagePath Storage path
1544 * @return bool
1545 */
1546 final public function isSingleShardPathInternal( $storagePath ) {
1547 list( , , $shard ) = $this->resolveStoragePath( $storagePath );
1548
1549 return ( $shard !== null );
1550 }
1551
1552 /**
1553 * Get the sharding config for a container.
1554 * If greater than 0, then all file storage paths within
1555 * the container are required to be hashed accordingly.
1556 *
1557 * @param string $container
1558 * @return array (integer levels, integer base, repeat flag) or (0, 0, false)
1559 */
1560 final protected function getContainerHashLevels( $container ) {
1561 if ( isset( $this->shardViaHashLevels[$container] ) ) {
1562 $config = $this->shardViaHashLevels[$container];
1563 $hashLevels = (int)$config['levels'];
1564 if ( $hashLevels == 1 || $hashLevels == 2 ) {
1565 $hashBase = (int)$config['base'];
1566 if ( $hashBase == 16 || $hashBase == 36 ) {
1567 return [ $hashLevels, $hashBase, $config['repeat'] ];
1568 }
1569 }
1570 }
1571
1572 return [ 0, 0, false ]; // no sharding
1573 }
1574
1575 /**
1576 * Get a list of full container shard suffixes for a container
1577 *
1578 * @param string $container
1579 * @return array
1580 */
1581 final protected function getContainerSuffixes( $container ) {
1582 $shards = [];
1583 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1584 if ( $digits > 0 ) {
1585 $numShards = $base ** $digits;
1586 for ( $index = 0; $index < $numShards; $index++ ) {
1587 $shards[] = '.' . Wikimedia\base_convert( $index, 10, $base, $digits );
1588 }
1589 }
1590
1591 return $shards;
1592 }
1593
1594 /**
1595 * Get the full container name, including the wiki ID prefix
1596 *
1597 * @param string $container
1598 * @return string
1599 */
1600 final protected function fullContainerName( $container ) {
1601 if ( $this->domainId != '' ) {
1602 return "{$this->domainId}-$container";
1603 } else {
1604 return $container;
1605 }
1606 }
1607
1608 /**
1609 * Resolve a container name, checking if it's allowed by the backend.
1610 * This is intended for internal use, such as encoding illegal chars.
1611 * Subclasses can override this to be more restrictive.
1612 *
1613 * @param string $container
1614 * @return string|null
1615 */
1616 protected function resolveContainerName( $container ) {
1617 return $container;
1618 }
1619
1620 /**
1621 * Resolve a relative storage path, checking if it's allowed by the backend.
1622 * This is intended for internal use, such as encoding illegal chars or perhaps
1623 * getting absolute paths (e.g. FS based backends). Note that the relative path
1624 * may be the empty string (e.g. the path is simply to the container).
1625 *
1626 * @param string $container Container name
1627 * @param string $relStoragePath Storage path relative to the container
1628 * @return string|null Path or null if not valid
1629 */
1630 protected function resolveContainerPath( $container, $relStoragePath ) {
1631 return $relStoragePath;
1632 }
1633
1634 /**
1635 * Get the cache key for a container
1636 *
1637 * @param string $container Resolved container name
1638 * @return string
1639 */
1640 private function containerCacheKey( $container ) {
1641 return "filebackend:{$this->name}:{$this->domainId}:container:{$container}";
1642 }
1643
1644 /**
1645 * Set the cached info for a container
1646 *
1647 * @param string $container Resolved container name
1648 * @param array $val Information to cache
1649 */
1650 final protected function setContainerCache( $container, array $val ) {
1651 $this->memCache->set( $this->containerCacheKey( $container ), $val, 14 * 86400 );
1652 }
1653
1654 /**
1655 * Delete the cached info for a container.
1656 * The cache key is salted for a while to prevent race conditions.
1657 *
1658 * @param string $container Resolved container name
1659 */
1660 final protected function deleteContainerCache( $container ) {
1661 if ( !$this->memCache->delete( $this->containerCacheKey( $container ), 300 ) ) {
1662 trigger_error( "Unable to delete stat cache for container $container." );
1663 }
1664 }
1665
1666 /**
1667 * Do a batch lookup from cache for container stats for all containers
1668 * used in a list of container names or storage paths objects.
1669 * This loads the persistent cache values into the process cache.
1670 *
1671 * @param array $items
1672 */
1673 final protected function primeContainerCache( array $items ) {
1674 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1675
1676 $paths = []; // list of storage paths
1677 $contNames = []; // (cache key => resolved container name)
1678 // Get all the paths/containers from the items...
1679 foreach ( $items as $item ) {
1680 if ( self::isStoragePath( $item ) ) {
1681 $paths[] = $item;
1682 } elseif ( is_string( $item ) ) { // full container name
1683 $contNames[$this->containerCacheKey( $item )] = $item;
1684 }
1685 }
1686 // Get all the corresponding cache keys for paths...
1687 foreach ( $paths as $path ) {
1688 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1689 if ( $fullCont !== null ) { // valid path for this backend
1690 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1691 }
1692 }
1693
1694 $contInfo = []; // (resolved container name => cache value)
1695 // Get all cache entries for these container cache keys...
1696 $values = $this->memCache->getMulti( array_keys( $contNames ) );
1697 foreach ( $values as $cacheKey => $val ) {
1698 $contInfo[$contNames[$cacheKey]] = $val;
1699 }
1700
1701 // Populate the container process cache for the backend...
1702 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1703 }
1704
1705 /**
1706 * Fill the backend-specific process cache given an array of
1707 * resolved container names and their corresponding cached info.
1708 * Only containers that actually exist should appear in the map.
1709 *
1710 * @param array $containerInfo Map of resolved container names to cached info
1711 */
1712 protected function doPrimeContainerCache( array $containerInfo ) {
1713 }
1714
1715 /**
1716 * Get the cache key for a file path
1717 *
1718 * @param string $path Normalized storage path
1719 * @return string
1720 */
1721 private function fileCacheKey( $path ) {
1722 return "filebackend:{$this->name}:{$this->domainId}:file:" . sha1( $path );
1723 }
1724
1725 /**
1726 * Set the cached stat info for a file path.
1727 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1728 * salting for the case when a file is created at a path were there was none before.
1729 *
1730 * @param string $path Storage path
1731 * @param array $val Stat information to cache
1732 */
1733 final protected function setFileCache( $path, array $val ) {
1734 $path = FileBackend::normalizeStoragePath( $path );
1735 if ( $path === null ) {
1736 return; // invalid storage path
1737 }
1738 $mtime = ConvertibleTimestamp::convert( TS_UNIX, $val['mtime'] );
1739 $ttl = $this->memCache->adaptiveTTL( $mtime, 7 * 86400, 300, 0.1 );
1740 $key = $this->fileCacheKey( $path );
1741 // Set the cache unless it is currently salted.
1742 $this->memCache->set( $key, $val, $ttl );
1743 }
1744
1745 /**
1746 * Delete the cached stat info for a file path.
1747 * The cache key is salted for a while to prevent race conditions.
1748 * Since negatives (404s) are not cached, this does not need to be called when
1749 * a file is created at a path were there was none before.
1750 *
1751 * @param string $path Storage path
1752 */
1753 final protected function deleteFileCache( $path ) {
1754 $path = FileBackend::normalizeStoragePath( $path );
1755 if ( $path === null ) {
1756 return; // invalid storage path
1757 }
1758 if ( !$this->memCache->delete( $this->fileCacheKey( $path ), 300 ) ) {
1759 trigger_error( "Unable to delete stat cache for file $path." );
1760 }
1761 }
1762
1763 /**
1764 * Do a batch lookup from cache for file stats for all paths
1765 * used in a list of storage paths or FileOp objects.
1766 * This loads the persistent cache values into the process cache.
1767 *
1768 * @param array $items List of storage paths
1769 */
1770 final protected function primeFileCache( array $items ) {
1771 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1772
1773 $paths = []; // list of storage paths
1774 $pathNames = []; // (cache key => storage path)
1775 // Get all the paths/containers from the items...
1776 foreach ( $items as $item ) {
1777 if ( self::isStoragePath( $item ) ) {
1778 $paths[] = FileBackend::normalizeStoragePath( $item );
1779 }
1780 }
1781 // Get rid of any paths that failed normalization...
1782 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1783 // Get all the corresponding cache keys for paths...
1784 foreach ( $paths as $path ) {
1785 list( , $rel, ) = $this->resolveStoragePath( $path );
1786 if ( $rel !== null ) { // valid path for this backend
1787 $pathNames[$this->fileCacheKey( $path )] = $path;
1788 }
1789 }
1790 // Get all cache entries for these file cache keys...
1791 $values = $this->memCache->getMulti( array_keys( $pathNames ) );
1792 foreach ( $values as $cacheKey => $val ) {
1793 $path = $pathNames[$cacheKey];
1794 if ( is_array( $val ) ) {
1795 $val['latest'] = false; // never completely trust cache
1796 $this->cheapCache->setField( $path, 'stat', $val );
1797 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1798 $this->cheapCache->setField( $path, 'sha1',
1799 [ 'hash' => $val['sha1'], 'latest' => false ] );
1800 }
1801 if ( isset( $val['xattr'] ) ) { // some backends store headers/metadata
1802 $val['xattr'] = self::normalizeXAttributes( $val['xattr'] );
1803 $this->cheapCache->setField( $path, 'xattr',
1804 [ 'map' => $val['xattr'], 'latest' => false ] );
1805 }
1806 }
1807 }
1808 }
1809
1810 /**
1811 * Normalize file headers/metadata to the FileBackend::getFileXAttributes() format
1812 *
1813 * @param array $xattr
1814 * @return array
1815 * @since 1.22
1816 */
1817 final protected static function normalizeXAttributes( array $xattr ) {
1818 $newXAttr = [ 'headers' => [], 'metadata' => [] ];
1819
1820 foreach ( $xattr['headers'] as $name => $value ) {
1821 $newXAttr['headers'][strtolower( $name )] = $value;
1822 }
1823
1824 foreach ( $xattr['metadata'] as $name => $value ) {
1825 $newXAttr['metadata'][strtolower( $name )] = $value;
1826 }
1827
1828 return $newXAttr;
1829 }
1830
1831 /**
1832 * Set the 'concurrency' option from a list of operation options
1833 *
1834 * @param array $opts Map of operation options
1835 * @return array
1836 */
1837 final protected function setConcurrencyFlags( array $opts ) {
1838 $opts['concurrency'] = 1; // off
1839 if ( $this->parallelize === 'implicit' ) {
1840 if ( !isset( $opts['parallelize'] ) || $opts['parallelize'] ) {
1841 $opts['concurrency'] = $this->concurrency;
1842 }
1843 } elseif ( $this->parallelize === 'explicit' ) {
1844 if ( !empty( $opts['parallelize'] ) ) {
1845 $opts['concurrency'] = $this->concurrency;
1846 }
1847 }
1848
1849 return $opts;
1850 }
1851
1852 /**
1853 * Get the content type to use in HEAD/GET requests for a file
1854 *
1855 * @param string $storagePath
1856 * @param string|null $content File data
1857 * @param string|null $fsPath File system path
1858 * @return string MIME type
1859 */
1860 protected function getContentType( $storagePath, $content, $fsPath ) {
1861 if ( $this->mimeCallback ) {
1862 return call_user_func_array( $this->mimeCallback, func_get_args() );
1863 }
1864
1865 $mime = ( $fsPath !== null ) ? mime_content_type( $fsPath ) : false;
1866 return $mime ?: 'unknown/unknown';
1867 }
1868 }