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