Revert "Limit searches at 500 per page"
[lhc/web/wiklou.git] / includes / filebackend / FileBackendStore.php
1 <?php
2 /**
3 * Base class for all backends using particular storage medium.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup FileBackend
22 * @author Aaron Schulz
23 */
24
25 /**
26 * @brief Base class for all backends using particular storage medium.
27 *
28 * This class defines the methods as abstract that subclasses must implement.
29 * Outside callers should *not* use functions with "Internal" in the name.
30 *
31 * The FileBackend operations are implemented using basic functions
32 * such as storeInternal(), copyInternal(), deleteInternal() and the like.
33 * This class is also responsible for path resolution and sanitization.
34 *
35 * @ingroup FileBackend
36 * @since 1.19
37 */
38 abstract class FileBackendStore extends FileBackend {
39 /** @var BagOStuff */
40 protected $memCache;
41 /** @var ProcessCacheLRU Map of paths to small (RAM/disk) cache items */
42 protected $cheapCache;
43 /** @var ProcessCacheLRU Map of paths to large (RAM/disk) cache items */
44 protected $expensiveCache;
45
46 /** @var array Map of container names to sharding config */
47 protected $shardViaHashLevels = array();
48
49 /** @var callback Method to get the MIME type of files */
50 protected $mimeCallback;
51
52 protected $maxFileSize = 4294967296; // integer bytes (4GiB)
53
54 const CACHE_TTL = 10; // integer; TTL in seconds for process cache entries
55 const CACHE_CHEAP_SIZE = 500; // integer; max entries in "cheap cache"
56 const CACHE_EXPENSIVE_SIZE = 5; // integer; max entries in "expensive cache"
57
58 /**
59 * @see FileBackend::__construct()
60 * Additional $config params include:
61 * - mimeCallback : Callback that takes (storage path, content, file system path) and
62 * returns the MIME type of the file or 'unknown/unknown'. The file
63 * system path parameter should be used if the content one is null.
64 *
65 * @param array $config
66 */
67 public function __construct( array $config ) {
68 parent::__construct( $config );
69 $this->mimeCallback = isset( $config['mimeCallback'] )
70 ? $config['mimeCallback']
71 : function ( $storagePath, $content, $fsPath ) {
72 // @TODO: handle the case of extension-less files using the contents
73 return StreamFile::contentTypeFromPath( $storagePath ) ?: 'unknown/unknown';
74 };
75 $this->memCache = new EmptyBagOStuff(); // disabled by default
76 $this->cheapCache = new ProcessCacheLRU( self::CACHE_CHEAP_SIZE );
77 $this->expensiveCache = new ProcessCacheLRU( 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 : Status will be returned immediately if supported.
112 * If the status 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 Status
119 */
120 final public function createInternal( array $params ) {
121 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
122 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
123 $status = Status::newFatal( 'backend-fail-maxsize',
124 $params['dst'], $this->maxFileSizeInternal() );
125 } else {
126 $status = $this->doCreateInternal( $params );
127 $this->clearCache( array( $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 Status
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 : Status will be returned immediately if supported.
153 * If the status 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 Status
160 */
161 final public function storeInternal( array $params ) {
162 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
163 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
164 $status = Status::newFatal( 'backend-fail-maxsize',
165 $params['dst'], $this->maxFileSizeInternal() );
166 } else {
167 $status = $this->doStoreInternal( $params );
168 $this->clearCache( array( $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 Status
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 : Status will be returned immediately if supported.
195 * If the status 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 Status
202 */
203 final public function copyInternal( array $params ) {
204 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
205 $status = $this->doCopyInternal( $params );
206 $this->clearCache( array( $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 Status
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 : Status will be returned immediately if supported.
229 * If the status is OK, then its value field will be
230 * set to a FileBackendStoreOpHandle object.
231 *
232 * @param array $params
233 * @return Status
234 */
235 final public function deleteInternal( array $params ) {
236 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
237 $status = $this->doDeleteInternal( $params );
238 $this->clearCache( array( $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 Status
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 : Status will be returned immediately if supported.
261 * If the status 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 Status
268 */
269 final public function moveInternal( array $params ) {
270 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
271 $status = $this->doMoveInternal( $params );
272 $this->clearCache( array( $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 Status
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( array( '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 : Status will be returned immediately if supported.
309 * If the status is OK, then its value field will be
310 * set to a FileBackendStoreOpHandle object.
311 *
312 * @param array $params
313 * @return Status
314 */
315 final public function describeInternal( array $params ) {
316 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
317 if ( count( $params['headers'] ) ) {
318 $status = $this->doDescribeInternal( $params );
319 $this->clearCache( array( $params['src'] ) );
320 $this->deleteFileCache( $params['src'] ); // persistent cache
321 } else {
322 $status = Status::newGood(); // nothing to do
323 }
324
325 return $status;
326 }
327
328 /**
329 * @see FileBackendStore::describeInternal()
330 * @param array $params
331 * @return Status
332 */
333 protected function doDescribeInternal( array $params ) {
334 return Status::newGood();
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 Status
343 */
344 final public function nullInternal( array $params ) {
345 return Status::newGood();
346 }
347
348 final public function concatenate( array $params ) {
349 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
350 $status = Status::newGood();
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 wfDebugLog( 'FileOperation', get_class( $this ) . " failed to concatenate " .
361 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 Status
372 */
373 protected function doConcatenate( array $params ) {
374 $status = Status::newGood();
375 $tmpPath = $params['dst']; // convenience
376 unset( $params['latest'] ); // sanity
377
378 // Check that the specified temp file is valid...
379 wfSuppressWarnings();
380 $ok = ( is_file( $tmpPath ) && filesize( $tmpPath ) == 0 );
381 wfRestoreWarnings();
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( array( '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 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
443 $status = Status::newGood();
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 wfDebug( __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 $container
468 * @param string $dir
469 * @param array $params
470 * @return Status
471 */
472 protected function doPrepareInternal( $container, $dir, array $params ) {
473 return Status::newGood();
474 }
475
476 final protected function doSecure( array $params ) {
477 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
478 $status = Status::newGood();
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 wfDebug( __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 $container
503 * @param string $dir
504 * @param array $params
505 * @return Status
506 */
507 protected function doSecureInternal( $container, $dir, array $params ) {
508 return Status::newGood();
509 }
510
511 final protected function doPublish( array $params ) {
512 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
513 $status = Status::newGood();
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 wfDebug( __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 $container
538 * @param string $dir
539 * @param array $params
540 * @return Status
541 */
542 protected function doPublishInternal( $container, $dir, array $params ) {
543 return Status::newGood();
544 }
545
546 final protected function doClean( array $params ) {
547 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
548 $status = Status::newGood();
549
550 // Recursive: first delete all empty subdirs recursively
551 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
552 $subDirsRel = $this->getTopDirectoryList( array( '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( array( '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 = array( $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 wfDebug( __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 $container
594 * @param string $dir
595 * @param array $params
596 * @return Status
597 */
598 protected function doCleanInternal( $container, $dir, array $params ) {
599 return Status::newGood();
600 }
601
602 final public function fileExists( array $params ) {
603 $section = new ProfileSection( __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 $section = new ProfileSection( __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 $section = new ProfileSection( __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 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
629 $latest = !empty( $params['latest'] ); // use latest data?
630 if ( !$this->cheapCache->has( $path, 'stat', self::CACHE_TTL ) ) {
631 $this->primeFileCache( array( $path ) ); // check persistent cache
632 }
633 if ( $this->cheapCache->has( $path, 'stat', self::CACHE_TTL ) ) {
634 $stat = $this->cheapCache->get( $path, 'stat' );
635 // If we want the latest data, check that this cached
636 // value was in fact fetched with the latest available data.
637 if ( is_array( $stat ) ) {
638 if ( !$latest || $stat['latest'] ) {
639 return $stat;
640 }
641 } elseif ( in_array( $stat, array( 'NOT_EXIST', 'NOT_EXIST_LATEST' ) ) ) {
642 if ( !$latest || $stat === 'NOT_EXIST_LATEST' ) {
643 return false;
644 }
645 }
646 }
647 wfProfileIn( __METHOD__ . '-miss-' . $this->name );
648 $stat = $this->doGetFileStat( $params );
649 wfProfileOut( __METHOD__ . '-miss-' . $this->name );
650 if ( is_array( $stat ) ) { // file exists
651 $stat['latest'] = $latest;
652 $this->cheapCache->set( $path, 'stat', $stat );
653 $this->setFileCache( $path, $stat ); // update persistent cache
654 if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata
655 $this->cheapCache->set( $path, 'sha1',
656 array( 'hash' => $stat['sha1'], 'latest' => $latest ) );
657 }
658 if ( isset( $stat['xattr'] ) ) { // some backends store headers/metadata
659 $stat['xattr'] = self::normalizeXAttributes( $stat['xattr'] );
660 $this->cheapCache->set( $path, 'xattr',
661 array( 'map' => $stat['xattr'], 'latest' => $latest ) );
662 }
663 } elseif ( $stat === false ) { // file does not exist
664 $this->cheapCache->set( $path, 'stat', $latest ? 'NOT_EXIST_LATEST' : 'NOT_EXIST' );
665 $this->cheapCache->set( $path, 'xattr', array( 'map' => false, 'latest' => $latest ) );
666 $this->cheapCache->set( $path, 'sha1', array( 'hash' => false, 'latest' => $latest ) );
667 wfDebug( __METHOD__ . ": File $path does not exist.\n" );
668 } else { // an error occurred
669 wfDebug( __METHOD__ . ": Could not stat file $path.\n" );
670 }
671
672 return $stat;
673 }
674
675 /**
676 * @see FileBackendStore::getFileStat()
677 */
678 abstract protected function doGetFileStat( array $params );
679
680 public function getFileContentsMulti( array $params ) {
681 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
682
683 $params = $this->setConcurrencyFlags( $params );
684 $contents = $this->doGetFileContentsMulti( $params );
685
686 return $contents;
687 }
688
689 /**
690 * @see FileBackendStore::getFileContentsMulti()
691 * @param array $params
692 * @return array
693 */
694 protected function doGetFileContentsMulti( array $params ) {
695 $contents = array();
696 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
697 wfSuppressWarnings();
698 $contents[$path] = $fsFile ? file_get_contents( $fsFile->getPath() ) : false;
699 wfRestoreWarnings();
700 }
701
702 return $contents;
703 }
704
705 final public function getFileXAttributes( array $params ) {
706 $path = self::normalizeStoragePath( $params['src'] );
707 if ( $path === null ) {
708 return false; // invalid storage path
709 }
710 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
711 $latest = !empty( $params['latest'] ); // use latest data?
712 if ( $this->cheapCache->has( $path, 'xattr', self::CACHE_TTL ) ) {
713 $stat = $this->cheapCache->get( $path, 'xattr' );
714 // If we want the latest data, check that this cached
715 // value was in fact fetched with the latest available data.
716 if ( !$latest || $stat['latest'] ) {
717 return $stat['map'];
718 }
719 }
720 wfProfileIn( __METHOD__ . '-miss' );
721 wfProfileIn( __METHOD__ . '-miss-' . $this->name );
722 $fields = $this->doGetFileXAttributes( $params );
723 $fields = is_array( $fields ) ? self::normalizeXAttributes( $fields ) : false;
724 wfProfileOut( __METHOD__ . '-miss-' . $this->name );
725 wfProfileOut( __METHOD__ . '-miss' );
726 $this->cheapCache->set( $path, 'xattr', array( 'map' => $fields, 'latest' => $latest ) );
727 return $fields;
728 }
729
730 /**
731 * @see FileBackendStore::getFileXAttributes()
732 * @return bool|string
733 */
734 protected function doGetFileXAttributes( array $params ) {
735 return array( 'headers' => array(), 'metadata' => array() ); // not supported
736 }
737
738 final public function getFileSha1Base36( array $params ) {
739 $path = self::normalizeStoragePath( $params['src'] );
740 if ( $path === null ) {
741 return false; // invalid storage path
742 }
743 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
744 $latest = !empty( $params['latest'] ); // use latest data?
745 if ( $this->cheapCache->has( $path, 'sha1', self::CACHE_TTL ) ) {
746 $stat = $this->cheapCache->get( $path, 'sha1' );
747 // If we want the latest data, check that this cached
748 // value was in fact fetched with the latest available data.
749 if ( !$latest || $stat['latest'] ) {
750 return $stat['hash'];
751 }
752 }
753 wfProfileIn( __METHOD__ . '-miss-' . $this->name );
754 $hash = $this->doGetFileSha1Base36( $params );
755 wfProfileOut( __METHOD__ . '-miss-' . $this->name );
756 $this->cheapCache->set( $path, 'sha1', array( 'hash' => $hash, 'latest' => $latest ) );
757
758 return $hash;
759 }
760
761 /**
762 * @see FileBackendStore::getFileSha1Base36()
763 * @param array $params
764 * @return bool|string
765 */
766 protected function doGetFileSha1Base36( array $params ) {
767 $fsFile = $this->getLocalReference( $params );
768 if ( !$fsFile ) {
769 return false;
770 } else {
771 return $fsFile->getSha1Base36();
772 }
773 }
774
775 final public function getFileProps( array $params ) {
776 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
777 $fsFile = $this->getLocalReference( $params );
778 $props = $fsFile ? $fsFile->getProps() : FSFile::placeholderProps();
779
780 return $props;
781 }
782
783 final public function getLocalReferenceMulti( array $params ) {
784 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
785
786 $params = $this->setConcurrencyFlags( $params );
787
788 $fsFiles = array(); // (path => FSFile)
789 $latest = !empty( $params['latest'] ); // use latest data?
790 // Reuse any files already in process cache...
791 foreach ( $params['srcs'] as $src ) {
792 $path = self::normalizeStoragePath( $src );
793 if ( $path === null ) {
794 $fsFiles[$src] = null; // invalid storage path
795 } elseif ( $this->expensiveCache->has( $path, 'localRef' ) ) {
796 $val = $this->expensiveCache->get( $path, 'localRef' );
797 // If we want the latest data, check that this cached
798 // value was in fact fetched with the latest available data.
799 if ( !$latest || $val['latest'] ) {
800 $fsFiles[$src] = $val['object'];
801 }
802 }
803 }
804 // Fetch local references of any remaning files...
805 $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
806 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
807 $fsFiles[$path] = $fsFile;
808 if ( $fsFile ) { // update the process cache...
809 $this->expensiveCache->set( $path, 'localRef',
810 array( 'object' => $fsFile, 'latest' => $latest ) );
811 }
812 }
813
814 return $fsFiles;
815 }
816
817 /**
818 * @see FileBackendStore::getLocalReferenceMulti()
819 * @param array $params
820 * @return array
821 */
822 protected function doGetLocalReferenceMulti( array $params ) {
823 return $this->doGetLocalCopyMulti( $params );
824 }
825
826 final public function getLocalCopyMulti( array $params ) {
827 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
828
829 $params = $this->setConcurrencyFlags( $params );
830 $tmpFiles = $this->doGetLocalCopyMulti( $params );
831
832 return $tmpFiles;
833 }
834
835 /**
836 * @see FileBackendStore::getLocalCopyMulti()
837 * @param array $params
838 * @return array
839 */
840 abstract protected function doGetLocalCopyMulti( array $params );
841
842 /**
843 * @see FileBackend::getFileHttpUrl()
844 * @param array $params
845 * @return string|null
846 */
847 public function getFileHttpUrl( array $params ) {
848 return null; // not supported
849 }
850
851 final public function streamFile( array $params ) {
852 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
853 $status = Status::newGood();
854
855 $info = $this->getFileStat( $params );
856 if ( !$info ) { // let StreamFile handle the 404
857 $status->fatal( 'backend-fail-notexists', $params['src'] );
858 }
859
860 // Set output buffer and HTTP headers for stream
861 $extraHeaders = isset( $params['headers'] ) ? $params['headers'] : array();
862 $res = StreamFile::prepareForStream( $params['src'], $info, $extraHeaders );
863 if ( $res == StreamFile::NOT_MODIFIED ) {
864 // do nothing; client cache is up to date
865 } elseif ( $res == StreamFile::READY_STREAM ) {
866 wfProfileIn( __METHOD__ . '-send-' . $this->name );
867 $status = $this->doStreamFile( $params );
868 wfProfileOut( __METHOD__ . '-send-' . $this->name );
869 if ( !$status->isOK() ) {
870 // Per bug 41113, nasty things can happen if bad cache entries get
871 // stuck in cache. It's also possible that this error can come up
872 // with simple race conditions. Clear out the stat cache to be safe.
873 $this->clearCache( array( $params['src'] ) );
874 $this->deleteFileCache( $params['src'] );
875 trigger_error( "Bad stat cache or race condition for file {$params['src']}." );
876 }
877 } else {
878 $status->fatal( 'backend-fail-stream', $params['src'] );
879 }
880
881 return $status;
882 }
883
884 /**
885 * @see FileBackendStore::streamFile()
886 * @param array $params
887 * @return Status
888 */
889 protected function doStreamFile( array $params ) {
890 $status = Status::newGood();
891
892 $fsFile = $this->getLocalReference( $params );
893 if ( !$fsFile ) {
894 $status->fatal( 'backend-fail-stream', $params['src'] );
895 } elseif ( !readfile( $fsFile->getPath() ) ) {
896 $status->fatal( 'backend-fail-stream', $params['src'] );
897 }
898
899 return $status;
900 }
901
902 final public function directoryExists( array $params ) {
903 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
904 if ( $dir === null ) {
905 return false; // invalid storage path
906 }
907 if ( $shard !== null ) { // confined to a single container/shard
908 return $this->doDirectoryExists( $fullCont, $dir, $params );
909 } else { // directory is on several shards
910 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
911 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
912 $res = false; // response
913 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
914 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
915 if ( $exists ) {
916 $res = true;
917 break; // found one!
918 } elseif ( $exists === null ) { // error?
919 $res = null; // if we don't find anything, it is indeterminate
920 }
921 }
922
923 return $res;
924 }
925 }
926
927 /**
928 * @see FileBackendStore::directoryExists()
929 *
930 * @param string $container Resolved container name
931 * @param string $dir Resolved path relative to container
932 * @param array $params
933 * @return bool|null
934 */
935 abstract protected function doDirectoryExists( $container, $dir, array $params );
936
937 final public function getDirectoryList( array $params ) {
938 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
939 if ( $dir === null ) { // invalid storage path
940 return null;
941 }
942 if ( $shard !== null ) {
943 // File listing is confined to a single container/shard
944 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
945 } else {
946 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
947 // File listing spans multiple containers/shards
948 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
949
950 return new FileBackendStoreShardDirIterator( $this,
951 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
952 }
953 }
954
955 /**
956 * Do not call this function from places outside FileBackend
957 *
958 * @see FileBackendStore::getDirectoryList()
959 *
960 * @param string $container Resolved container name
961 * @param string $dir Resolved path relative to container
962 * @param array $params
963 * @return Traversable|Array|null Returns null on failure
964 */
965 abstract public function getDirectoryListInternal( $container, $dir, array $params );
966
967 final public function getFileList( array $params ) {
968 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
969 if ( $dir === null ) { // invalid storage path
970 return null;
971 }
972 if ( $shard !== null ) {
973 // File listing is confined to a single container/shard
974 return $this->getFileListInternal( $fullCont, $dir, $params );
975 } else {
976 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
977 // File listing spans multiple containers/shards
978 list( , $shortCont, ) = self::splitStoragePath( $params['dir'] );
979
980 return new FileBackendStoreShardFileIterator( $this,
981 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
982 }
983 }
984
985 /**
986 * Do not call this function from places outside FileBackend
987 *
988 * @see FileBackendStore::getFileList()
989 *
990 * @param string $container Resolved container name
991 * @param string $dir Resolved path relative to container
992 * @param array $params
993 * @return Traversable|Array|null Returns null on failure
994 */
995 abstract public function getFileListInternal( $container, $dir, array $params );
996
997 /**
998 * Return a list of FileOp objects from a list of operations.
999 * Do not call this function from places outside FileBackend.
1000 *
1001 * The result must have the same number of items as the input.
1002 * An exception is thrown if an unsupported operation is requested.
1003 *
1004 * @param array $ops Same format as doOperations()
1005 * @return array List of FileOp objects
1006 * @throws FileBackendError
1007 */
1008 final public function getOperationsInternal( array $ops ) {
1009 $supportedOps = array(
1010 'store' => 'StoreFileOp',
1011 'copy' => 'CopyFileOp',
1012 'move' => 'MoveFileOp',
1013 'delete' => 'DeleteFileOp',
1014 'create' => 'CreateFileOp',
1015 'describe' => 'DescribeFileOp',
1016 'null' => 'NullFileOp'
1017 );
1018
1019 $performOps = array(); // array of FileOp objects
1020 // Build up ordered array of FileOps...
1021 foreach ( $ops as $operation ) {
1022 $opName = $operation['op'];
1023 if ( isset( $supportedOps[$opName] ) ) {
1024 $class = $supportedOps[$opName];
1025 // Get params for this operation
1026 $params = $operation;
1027 // Append the FileOp class
1028 $performOps[] = new $class( $this, $params );
1029 } else {
1030 throw new FileBackendError( "Operation '$opName' is not supported." );
1031 }
1032 }
1033
1034 return $performOps;
1035 }
1036
1037 /**
1038 * Get a list of storage paths to lock for a list of operations
1039 * Returns an array with LockManager::LOCK_UW (shared locks) and
1040 * LockManager::LOCK_EX (exclusive locks) keys, each corresponding
1041 * to a list of storage paths to be locked. All returned paths are
1042 * normalized.
1043 *
1044 * @param array $performOps List of FileOp objects
1045 * @return array (LockManager::LOCK_UW => path list, LockManager::LOCK_EX => path list)
1046 */
1047 final public function getPathsToLockForOpsInternal( array $performOps ) {
1048 // Build up a list of files to lock...
1049 $paths = array( 'sh' => array(), 'ex' => array() );
1050 foreach ( $performOps as $fileOp ) {
1051 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1052 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1053 }
1054 // Optimization: if doing an EX lock anyway, don't also set an SH one
1055 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1056 // Get a shared lock on the parent directory of each path changed
1057 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1058
1059 return array(
1060 LockManager::LOCK_UW => $paths['sh'],
1061 LockManager::LOCK_EX => $paths['ex']
1062 );
1063 }
1064
1065 public function getScopedLocksForOps( array $ops, Status $status ) {
1066 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1067
1068 return array( $this->getScopedFileLocks( $paths, 'mixed', $status ) );
1069 }
1070
1071 final protected function doOperationsInternal( array $ops, array $opts ) {
1072 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
1073 $status = Status::newGood();
1074
1075 // Fix up custom header name/value pairs...
1076 $ops = array_map( array( $this, 'stripInvalidHeadersFromOp' ), $ops );
1077
1078 // Build up a list of FileOps...
1079 $performOps = $this->getOperationsInternal( $ops );
1080
1081 // Acquire any locks as needed...
1082 if ( empty( $opts['nonLocking'] ) ) {
1083 // Build up a list of files to lock...
1084 $paths = $this->getPathsToLockForOpsInternal( $performOps );
1085 // Try to lock those files for the scope of this function...
1086 $scopeLock = $this->getScopedFileLocks( $paths, 'mixed', $status );
1087 if ( !$status->isOK() ) {
1088 return $status; // abort
1089 }
1090 }
1091
1092 // Clear any file cache entries (after locks acquired)
1093 if ( empty( $opts['preserveCache'] ) ) {
1094 $this->clearCache();
1095 }
1096
1097 // Load from the persistent file and container caches
1098 $this->primeFileCache( $performOps );
1099 $this->primeContainerCache( $performOps );
1100
1101 // Actually attempt the operation batch...
1102 $opts = $this->setConcurrencyFlags( $opts );
1103 $subStatus = FileOpBatch::attempt( $performOps, $opts, $this->fileJournal );
1104
1105 // Merge errors into status fields
1106 $status->merge( $subStatus );
1107 $status->success = $subStatus->success; // not done in merge()
1108
1109 return $status;
1110 }
1111
1112 final protected function doQuickOperationsInternal( array $ops ) {
1113 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
1114 $status = Status::newGood();
1115
1116 // Fix up custom header name/value pairs...
1117 $ops = array_map( array( $this, 'stripInvalidHeadersFromOp' ), $ops );
1118
1119 // Clear any file cache entries
1120 $this->clearCache();
1121
1122 $supportedOps = array( 'create', 'store', 'copy', 'move', 'delete', 'describe', 'null' );
1123 $async = ( $this->parallelize === 'implicit' && count( $ops ) > 1 );
1124 $maxConcurrency = $this->concurrency; // throttle
1125
1126 $statuses = array(); // array of (index => Status)
1127 $fileOpHandles = array(); // list of (index => handle) arrays
1128 $curFileOpHandles = array(); // current handle batch
1129 // Perform the sync-only ops and build up op handles for the async ops...
1130 foreach ( $ops as $index => $params ) {
1131 if ( !in_array( $params['op'], $supportedOps ) ) {
1132 throw new FileBackendError( "Operation '{$params['op']}' is not supported." );
1133 }
1134 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1135 $subStatus = $this->$method( array( 'async' => $async ) + $params );
1136 if ( $subStatus->value instanceof FileBackendStoreOpHandle ) { // async
1137 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1138 $fileOpHandles[] = $curFileOpHandles; // push this batch
1139 $curFileOpHandles = array();
1140 }
1141 $curFileOpHandles[$index] = $subStatus->value; // keep index
1142 } else { // error or completed
1143 $statuses[$index] = $subStatus; // keep index
1144 }
1145 }
1146 if ( count( $curFileOpHandles ) ) {
1147 $fileOpHandles[] = $curFileOpHandles; // last batch
1148 }
1149 // Do all the async ops that can be done concurrently...
1150 foreach ( $fileOpHandles as $fileHandleBatch ) {
1151 $statuses = $statuses + $this->executeOpHandlesInternal( $fileHandleBatch );
1152 }
1153 // Marshall and merge all the responses...
1154 foreach ( $statuses as $index => $subStatus ) {
1155 $status->merge( $subStatus );
1156 if ( $subStatus->isOK() ) {
1157 $status->success[$index] = true;
1158 ++$status->successCount;
1159 } else {
1160 $status->success[$index] = false;
1161 ++$status->failCount;
1162 }
1163 }
1164
1165 return $status;
1166 }
1167
1168 /**
1169 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1170 * The resulting Status object fields will correspond
1171 * to the order in which the handles where given.
1172 *
1173 * @param array $fileOpHandles
1174 * @throws FileBackendError
1175 * @internal param array $handles List of FileBackendStoreOpHandle objects
1176 * @return array Map of Status objects
1177 */
1178 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1179 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
1180
1181 foreach ( $fileOpHandles as $fileOpHandle ) {
1182 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle ) ) {
1183 throw new FileBackendError( "Given a non-FileBackendStoreOpHandle object." );
1184 } elseif ( $fileOpHandle->backend->getName() !== $this->getName() ) {
1185 throw new FileBackendError( "Given a FileBackendStoreOpHandle for the wrong backend." );
1186 }
1187 }
1188 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1189 foreach ( $fileOpHandles as $fileOpHandle ) {
1190 $fileOpHandle->closeResources();
1191 }
1192
1193 return $res;
1194 }
1195
1196 /**
1197 * @see FileBackendStore::executeOpHandlesInternal()
1198 * @param array $fileOpHandles
1199 * @throws FileBackendError
1200 * @return array List of corresponding Status objects
1201 */
1202 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1203 if ( count( $fileOpHandles ) ) {
1204 throw new FileBackendError( "This backend supports no asynchronous operations." );
1205 }
1206
1207 return array();
1208 }
1209
1210 /**
1211 * Strip long HTTP headers from a file operation.
1212 * Most headers are just numbers, but some are allowed to be long.
1213 * This function is useful for cleaning up headers and avoiding backend
1214 * specific errors, especially in the middle of batch file operations.
1215 *
1216 * @param array $op Same format as doOperation()
1217 * @return array
1218 */
1219 protected function stripInvalidHeadersFromOp( array $op ) {
1220 static $longs = array( 'Content-Disposition' );
1221 if ( isset( $op['headers'] ) ) { // op sets HTTP headers
1222 foreach ( $op['headers'] as $name => $value ) {
1223 $maxHVLen = in_array( $name, $longs ) ? INF : 255;
1224 if ( strlen( $name ) > 255 || strlen( $value ) > $maxHVLen ) {
1225 trigger_error( "Header '$name: $value' is too long." );
1226 unset( $op['headers'][$name] );
1227 } elseif ( !strlen( $value ) ) {
1228 $op['headers'][$name] = ''; // null/false => ""
1229 }
1230 }
1231 }
1232
1233 return $op;
1234 }
1235
1236 final public function preloadCache( array $paths ) {
1237 $fullConts = array(); // full container names
1238 foreach ( $paths as $path ) {
1239 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1240 $fullConts[] = $fullCont;
1241 }
1242 // Load from the persistent file and container caches
1243 $this->primeContainerCache( $fullConts );
1244 $this->primeFileCache( $paths );
1245 }
1246
1247 final public function clearCache( array $paths = null ) {
1248 if ( is_array( $paths ) ) {
1249 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1250 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1251 }
1252 if ( $paths === null ) {
1253 $this->cheapCache->clear();
1254 $this->expensiveCache->clear();
1255 } else {
1256 foreach ( $paths as $path ) {
1257 $this->cheapCache->clear( $path );
1258 $this->expensiveCache->clear( $path );
1259 }
1260 }
1261 $this->doClearCache( $paths );
1262 }
1263
1264 /**
1265 * Clears any additional stat caches for storage paths
1266 *
1267 * @see FileBackend::clearCache()
1268 *
1269 * @param array $paths Storage paths (optional)
1270 */
1271 protected function doClearCache( array $paths = null ) {
1272 }
1273
1274 /**
1275 * Is this a key/value store where directories are just virtual?
1276 * Virtual directories exists in so much as files exists that are
1277 * prefixed with the directory path followed by a forward slash.
1278 *
1279 * @return bool
1280 */
1281 abstract protected function directoriesAreVirtual();
1282
1283 /**
1284 * Check if a container name is valid.
1285 * This checks for for length and illegal characters.
1286 *
1287 * @param string $container
1288 * @return bool
1289 */
1290 final protected static function isValidContainerName( $container ) {
1291 // This accounts for Swift and S3 restrictions while leaving room
1292 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1293 // This disallows directory separators or traversal characters.
1294 // Note that matching strings URL encode to the same string;
1295 // in Swift, the length restriction is *after* URL encoding.
1296 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1297 }
1298
1299 /**
1300 * Splits a storage path into an internal container name,
1301 * an internal relative file name, and a container shard suffix.
1302 * Any shard suffix is already appended to the internal container name.
1303 * This also checks that the storage path is valid and within this backend.
1304 *
1305 * If the container is sharded but a suffix could not be determined,
1306 * this means that the path can only refer to a directory and can only
1307 * be scanned by looking in all the container shards.
1308 *
1309 * @param string $storagePath
1310 * @return array (container, path, container suffix) or (null, null, null) if invalid
1311 */
1312 final protected function resolveStoragePath( $storagePath ) {
1313 list( $backend, $container, $relPath ) = self::splitStoragePath( $storagePath );
1314 if ( $backend === $this->name ) { // must be for this backend
1315 $relPath = self::normalizeContainerPath( $relPath );
1316 if ( $relPath !== null ) {
1317 // Get shard for the normalized path if this container is sharded
1318 $cShard = $this->getContainerShard( $container, $relPath );
1319 // Validate and sanitize the relative path (backend-specific)
1320 $relPath = $this->resolveContainerPath( $container, $relPath );
1321 if ( $relPath !== null ) {
1322 // Prepend any wiki ID prefix to the container name
1323 $container = $this->fullContainerName( $container );
1324 if ( self::isValidContainerName( $container ) ) {
1325 // Validate and sanitize the container name (backend-specific)
1326 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1327 if ( $container !== null ) {
1328 return array( $container, $relPath, $cShard );
1329 }
1330 }
1331 }
1332 }
1333 }
1334
1335 return array( null, null, null );
1336 }
1337
1338 /**
1339 * Like resolveStoragePath() except null values are returned if
1340 * the container is sharded and the shard could not be determined
1341 * or if the path ends with '/'. The later case is illegal for FS
1342 * backends and can confuse listings for object store backends.
1343 *
1344 * This function is used when resolving paths that must be valid
1345 * locations for files. Directory and listing functions should
1346 * generally just use resolveStoragePath() instead.
1347 *
1348 * @see FileBackendStore::resolveStoragePath()
1349 *
1350 * @param string $storagePath
1351 * @return array (container, path) or (null, null) if invalid
1352 */
1353 final protected function resolveStoragePathReal( $storagePath ) {
1354 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1355 if ( $cShard !== null && substr( $relPath, -1 ) !== '/' ) {
1356 return array( $container, $relPath );
1357 }
1358
1359 return array( null, null );
1360 }
1361
1362 /**
1363 * Get the container name shard suffix for a given path.
1364 * Any empty suffix means the container is not sharded.
1365 *
1366 * @param string $container Container name
1367 * @param string $relPath Storage path relative to the container
1368 * @return string|null Returns null if shard could not be determined
1369 */
1370 final protected function getContainerShard( $container, $relPath ) {
1371 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1372 if ( $levels == 1 || $levels == 2 ) {
1373 // Hash characters are either base 16 or 36
1374 $char = ( $base == 36 ) ? '[0-9a-z]' : '[0-9a-f]';
1375 // Get a regex that represents the shard portion of paths.
1376 // The concatenation of the captures gives us the shard.
1377 if ( $levels === 1 ) { // 16 or 36 shards per container
1378 $hashDirRegex = '(' . $char . ')';
1379 } else { // 256 or 1296 shards per container
1380 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1381 $hashDirRegex = $char . '/(' . $char . '{2})';
1382 } else { // short hash dir format (e.g. "a/b/c")
1383 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1384 }
1385 }
1386 // Allow certain directories to be above the hash dirs so as
1387 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1388 // They must be 2+ chars to avoid any hash directory ambiguity.
1389 $m = array();
1390 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1391 return '.' . implode( '', array_slice( $m, 1 ) );
1392 }
1393
1394 return null; // failed to match
1395 }
1396
1397 return ''; // no sharding
1398 }
1399
1400 /**
1401 * Check if a storage path maps to a single shard.
1402 * Container dirs like "a", where the container shards on "x/xy",
1403 * can reside on several shards. Such paths are tricky to handle.
1404 *
1405 * @param string $storagePath Storage path
1406 * @return bool
1407 */
1408 final public function isSingleShardPathInternal( $storagePath ) {
1409 list( , , $shard ) = $this->resolveStoragePath( $storagePath );
1410
1411 return ( $shard !== null );
1412 }
1413
1414 /**
1415 * Get the sharding config for a container.
1416 * If greater than 0, then all file storage paths within
1417 * the container are required to be hashed accordingly.
1418 *
1419 * @param string $container
1420 * @return array (integer levels, integer base, repeat flag) or (0, 0, false)
1421 */
1422 final protected function getContainerHashLevels( $container ) {
1423 if ( isset( $this->shardViaHashLevels[$container] ) ) {
1424 $config = $this->shardViaHashLevels[$container];
1425 $hashLevels = (int)$config['levels'];
1426 if ( $hashLevels == 1 || $hashLevels == 2 ) {
1427 $hashBase = (int)$config['base'];
1428 if ( $hashBase == 16 || $hashBase == 36 ) {
1429 return array( $hashLevels, $hashBase, $config['repeat'] );
1430 }
1431 }
1432 }
1433
1434 return array( 0, 0, false ); // no sharding
1435 }
1436
1437 /**
1438 * Get a list of full container shard suffixes for a container
1439 *
1440 * @param string $container
1441 * @return array
1442 */
1443 final protected function getContainerSuffixes( $container ) {
1444 $shards = array();
1445 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1446 if ( $digits > 0 ) {
1447 $numShards = pow( $base, $digits );
1448 for ( $index = 0; $index < $numShards; $index++ ) {
1449 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1450 }
1451 }
1452
1453 return $shards;
1454 }
1455
1456 /**
1457 * Get the full container name, including the wiki ID prefix
1458 *
1459 * @param string $container
1460 * @return string
1461 */
1462 final protected function fullContainerName( $container ) {
1463 if ( $this->wikiId != '' ) {
1464 return "{$this->wikiId}-$container";
1465 } else {
1466 return $container;
1467 }
1468 }
1469
1470 /**
1471 * Resolve a container name, checking if it's allowed by the backend.
1472 * This is intended for internal use, such as encoding illegal chars.
1473 * Subclasses can override this to be more restrictive.
1474 *
1475 * @param string $container
1476 * @return string|null
1477 */
1478 protected function resolveContainerName( $container ) {
1479 return $container;
1480 }
1481
1482 /**
1483 * Resolve a relative storage path, checking if it's allowed by the backend.
1484 * This is intended for internal use, such as encoding illegal chars or perhaps
1485 * getting absolute paths (e.g. FS based backends). Note that the relative path
1486 * may be the empty string (e.g. the path is simply to the container).
1487 *
1488 * @param string $container Container name
1489 * @param string $relStoragePath Storage path relative to the container
1490 * @return string|null Path or null if not valid
1491 */
1492 protected function resolveContainerPath( $container, $relStoragePath ) {
1493 return $relStoragePath;
1494 }
1495
1496 /**
1497 * Get the cache key for a container
1498 *
1499 * @param string $container Resolved container name
1500 * @return string
1501 */
1502 private function containerCacheKey( $container ) {
1503 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1504 }
1505
1506 /**
1507 * Set the cached info for a container
1508 *
1509 * @param string $container Resolved container name
1510 * @param array $val Information to cache
1511 */
1512 final protected function setContainerCache( $container, array $val ) {
1513 $this->memCache->add( $this->containerCacheKey( $container ), $val, 14 * 86400 );
1514 }
1515
1516 /**
1517 * Delete the cached info for a container.
1518 * The cache key is salted for a while to prevent race conditions.
1519 *
1520 * @param string $container Resolved container name
1521 */
1522 final protected function deleteContainerCache( $container ) {
1523 if ( !$this->memCache->set( $this->containerCacheKey( $container ), 'PURGED', 300 ) ) {
1524 trigger_error( "Unable to delete stat cache for container $container." );
1525 }
1526 }
1527
1528 /**
1529 * Do a batch lookup from cache for container stats for all containers
1530 * used in a list of container names, storage paths, or FileOp objects.
1531 * This loads the persistent cache values into the process cache.
1532 *
1533 * @param array $items
1534 */
1535 final protected function primeContainerCache( array $items ) {
1536 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
1537
1538 $paths = array(); // list of storage paths
1539 $contNames = array(); // (cache key => resolved container name)
1540 // Get all the paths/containers from the items...
1541 foreach ( $items as $item ) {
1542 if ( $item instanceof FileOp ) {
1543 $paths = array_merge( $paths, $item->storagePathsRead() );
1544 $paths = array_merge( $paths, $item->storagePathsChanged() );
1545 } elseif ( self::isStoragePath( $item ) ) {
1546 $paths[] = $item;
1547 } elseif ( is_string( $item ) ) { // full container name
1548 $contNames[$this->containerCacheKey( $item )] = $item;
1549 }
1550 }
1551 // Get all the corresponding cache keys for paths...
1552 foreach ( $paths as $path ) {
1553 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1554 if ( $fullCont !== null ) { // valid path for this backend
1555 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1556 }
1557 }
1558
1559 $contInfo = array(); // (resolved container name => cache value)
1560 // Get all cache entries for these container cache keys...
1561 $values = $this->memCache->getMulti( array_keys( $contNames ) );
1562 foreach ( $values as $cacheKey => $val ) {
1563 $contInfo[$contNames[$cacheKey]] = $val;
1564 }
1565
1566 // Populate the container process cache for the backend...
1567 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1568 }
1569
1570 /**
1571 * Fill the backend-specific process cache given an array of
1572 * resolved container names and their corresponding cached info.
1573 * Only containers that actually exist should appear in the map.
1574 *
1575 * @param array $containerInfo Map of resolved container names to cached info
1576 */
1577 protected function doPrimeContainerCache( array $containerInfo ) {
1578 }
1579
1580 /**
1581 * Get the cache key for a file path
1582 *
1583 * @param string $path Normalized storage path
1584 * @return string
1585 */
1586 private function fileCacheKey( $path ) {
1587 return wfMemcKey( 'backend', $this->getName(), 'file', sha1( $path ) );
1588 }
1589
1590 /**
1591 * Set the cached stat info for a file path.
1592 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1593 * salting for the case when a file is created at a path were there was none before.
1594 *
1595 * @param string $path Storage path
1596 * @param array $val Stat information to cache
1597 */
1598 final protected function setFileCache( $path, array $val ) {
1599 $path = FileBackend::normalizeStoragePath( $path );
1600 if ( $path === null ) {
1601 return; // invalid storage path
1602 }
1603 $age = time() - wfTimestamp( TS_UNIX, $val['mtime'] );
1604 $ttl = min( 7 * 86400, max( 300, floor( .1 * $age ) ) );
1605 $this->memCache->add( $this->fileCacheKey( $path ), $val, $ttl );
1606 }
1607
1608 /**
1609 * Delete the cached stat info for a file path.
1610 * The cache key is salted for a while to prevent race conditions.
1611 * Since negatives (404s) are not cached, this does not need to be called when
1612 * a file is created at a path were there was none before.
1613 *
1614 * @param string $path Storage path
1615 */
1616 final protected function deleteFileCache( $path ) {
1617 $path = FileBackend::normalizeStoragePath( $path );
1618 if ( $path === null ) {
1619 return; // invalid storage path
1620 }
1621 if ( !$this->memCache->set( $this->fileCacheKey( $path ), 'PURGED', 300 ) ) {
1622 trigger_error( "Unable to delete stat cache for file $path." );
1623 }
1624 }
1625
1626 /**
1627 * Do a batch lookup from cache for file stats for all paths
1628 * used in a list of storage paths or FileOp objects.
1629 * This loads the persistent cache values into the process cache.
1630 *
1631 * @param array $items List of storage paths or FileOps
1632 */
1633 final protected function primeFileCache( array $items ) {
1634 $section = new ProfileSection( __METHOD__ . "-{$this->name}" );
1635
1636 $paths = array(); // list of storage paths
1637 $pathNames = array(); // (cache key => storage path)
1638 // Get all the paths/containers from the items...
1639 foreach ( $items as $item ) {
1640 if ( $item instanceof FileOp ) {
1641 $paths = array_merge( $paths, $item->storagePathsRead() );
1642 $paths = array_merge( $paths, $item->storagePathsChanged() );
1643 } elseif ( self::isStoragePath( $item ) ) {
1644 $paths[] = FileBackend::normalizeStoragePath( $item );
1645 }
1646 }
1647 // Get rid of any paths that failed normalization...
1648 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1649 // Get all the corresponding cache keys for paths...
1650 foreach ( $paths as $path ) {
1651 list( , $rel, ) = $this->resolveStoragePath( $path );
1652 if ( $rel !== null ) { // valid path for this backend
1653 $pathNames[$this->fileCacheKey( $path )] = $path;
1654 }
1655 }
1656 // Get all cache entries for these container cache keys...
1657 $values = $this->memCache->getMulti( array_keys( $pathNames ) );
1658 foreach ( $values as $cacheKey => $val ) {
1659 if ( is_array( $val ) ) {
1660 $path = $pathNames[$cacheKey];
1661 $this->cheapCache->set( $path, 'stat', $val );
1662 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1663 $this->cheapCache->set( $path, 'sha1',
1664 array( 'hash' => $val['sha1'], 'latest' => $val['latest'] ) );
1665 }
1666 if ( isset( $val['xattr'] ) ) { // some backends store headers/metadata
1667 $stat['xattr'] = self::normalizeXAttributes( $stat['xattr'] );
1668 $this->cheapCache->set( $path, 'xattr',
1669 array( 'map' => $val['xattr'], 'latest' => $val['latest'] ) );
1670 }
1671 }
1672 }
1673 }
1674
1675 /**
1676 * Normalize file headers/metadata to the FileBackend::getFileXAttributes() format
1677 *
1678 * @param array $xattr
1679 * @return array
1680 * @since 1.22
1681 */
1682 final protected static function normalizeXAttributes( array $xattr ) {
1683 $newXAttr = array( 'headers' => array(), 'metadata' => array() );
1684 foreach ( $xattr['headers'] as $name => $value ) {
1685 $newXAttr['headers'][strtolower( $name )] = $value;
1686 }
1687 foreach ( $xattr['metadata'] as $name => $value ) {
1688 $newXAttr['metadata'][strtolower( $name )] = $value;
1689 }
1690 return $newXAttr;
1691 }
1692
1693 /**
1694 * Set the 'concurrency' option from a list of operation options
1695 *
1696 * @param array $opts Map of operation options
1697 * @return array
1698 */
1699 final protected function setConcurrencyFlags( array $opts ) {
1700 $opts['concurrency'] = 1; // off
1701 if ( $this->parallelize === 'implicit' ) {
1702 if ( !isset( $opts['parallelize'] ) || $opts['parallelize'] ) {
1703 $opts['concurrency'] = $this->concurrency;
1704 }
1705 } elseif ( $this->parallelize === 'explicit' ) {
1706 if ( !empty( $opts['parallelize'] ) ) {
1707 $opts['concurrency'] = $this->concurrency;
1708 }
1709 }
1710
1711 return $opts;
1712 }
1713
1714 /**
1715 * Get the content type to use in HEAD/GET requests for a file
1716 *
1717 * @param string $storagePath
1718 * @param string|null $content File data
1719 * @param string|null $fsPath File system path
1720 * @return MIME type
1721 */
1722 protected function getContentType( $storagePath, $content, $fsPath ) {
1723 return call_user_func_array( $this->mimeCallback, func_get_args() );
1724 }
1725 }
1726
1727 /**
1728 * FileBackendStore helper class for performing asynchronous file operations.
1729 *
1730 * For example, calling FileBackendStore::createInternal() with the "async"
1731 * param flag may result in a Status that contains this object as a value.
1732 * This class is largely backend-specific and is mostly just "magic" to be
1733 * passed to FileBackendStore::executeOpHandlesInternal().
1734 */
1735 abstract class FileBackendStoreOpHandle {
1736 /** @var array */
1737 public $params = array(); // params to caller functions
1738 /** @var FileBackendStore */
1739 public $backend;
1740 /** @var array */
1741 public $resourcesToClose = array();
1742
1743 public $call; // string; name that identifies the function called
1744
1745 /**
1746 * Close all open file handles
1747 */
1748 public function closeResources() {
1749 array_map( 'fclose', $this->resourcesToClose );
1750 }
1751 }
1752
1753 /**
1754 * FileBackendStore helper function to handle listings that span container shards.
1755 * Do not use this class from places outside of FileBackendStore.
1756 *
1757 * @ingroup FileBackend
1758 */
1759 abstract class FileBackendStoreShardListIterator extends FilterIterator {
1760 /** @var FileBackendStore */
1761 protected $backend;
1762
1763 /** @var array */
1764 protected $params;
1765
1766 /** @var string Full container name */
1767 protected $container;
1768
1769 /** @var string Resolved relative path */
1770 protected $directory;
1771
1772 /** @var array */
1773 protected $multiShardPaths = array(); // (rel path => 1)
1774
1775 /**
1776 * @param FileBackendStore $backend
1777 * @param string $container Full storage container name
1778 * @param string $dir Storage directory relative to container
1779 * @param array $suffixes List of container shard suffixes
1780 * @param array $params
1781 */
1782 public function __construct(
1783 FileBackendStore $backend, $container, $dir, array $suffixes, array $params
1784 ) {
1785 $this->backend = $backend;
1786 $this->container = $container;
1787 $this->directory = $dir;
1788 $this->params = $params;
1789
1790 $iter = new AppendIterator();
1791 foreach ( $suffixes as $suffix ) {
1792 $iter->append( $this->listFromShard( $this->container . $suffix ) );
1793 }
1794
1795 parent::__construct( $iter );
1796 }
1797
1798 public function accept() {
1799 $rel = $this->getInnerIterator()->current(); // path relative to given directory
1800 $path = $this->params['dir'] . "/{$rel}"; // full storage path
1801 if ( $this->backend->isSingleShardPathInternal( $path ) ) {
1802 return true; // path is only on one shard; no issue with duplicates
1803 } elseif ( isset( $this->multiShardPaths[$rel] ) ) {
1804 // Don't keep listing paths that are on multiple shards
1805 return false;
1806 } else {
1807 $this->multiShardPaths[$rel] = 1;
1808
1809 return true;
1810 }
1811 }
1812
1813 public function rewind() {
1814 parent::rewind();
1815 $this->multiShardPaths = array();
1816 }
1817
1818 /**
1819 * Get the list for a given container shard
1820 *
1821 * @param string $container Resolved container name
1822 * @return Iterator
1823 */
1824 abstract protected function listFromShard( $container );
1825 }
1826
1827 /**
1828 * Iterator for listing directories
1829 */
1830 class FileBackendStoreShardDirIterator extends FileBackendStoreShardListIterator {
1831 protected function listFromShard( $container ) {
1832 $list = $this->backend->getDirectoryListInternal(
1833 $container, $this->directory, $this->params );
1834 if ( $list === null ) {
1835 return new ArrayIterator( array() );
1836 } else {
1837 return is_array( $list ) ? new ArrayIterator( $list ) : $list;
1838 }
1839 }
1840 }
1841
1842 /**
1843 * Iterator for listing regular files
1844 */
1845 class FileBackendStoreShardFileIterator extends FileBackendStoreShardListIterator {
1846 protected function listFromShard( $container ) {
1847 $list = $this->backend->getFileListInternal(
1848 $container, $this->directory, $this->params );
1849 if ( $list === null ) {
1850 return new ArrayIterator( array() );
1851 } else {
1852 return is_array( $list ) ? new ArrayIterator( $list ) : $list;
1853 }
1854 }
1855 }