[FileBackend] Optimize the case were no operations are provided.
[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 if ( !count( $ops ) ) {
1138 return $status; // nothing to do
1139 }
1140
1141 // Fix up custom header name/value pairs...
1142 $ops = array_map( array( $this, 'stripInvalidHeadersFromOp' ), $ops );
1143
1144 // Build up a list of FileOps...
1145 $performOps = $this->getOperationsInternal( $ops );
1146
1147 // Acquire any locks as needed...
1148 if ( empty( $opts['nonLocking'] ) ) {
1149 // Build up a list of files to lock...
1150 $paths = $this->getPathsToLockForOpsInternal( $performOps );
1151 // Try to lock those files for the scope of this function...
1152 $scopeLockS = $this->getScopedFileLocks( $paths['sh'], LockManager::LOCK_UW, $status );
1153 $scopeLockE = $this->getScopedFileLocks( $paths['ex'], LockManager::LOCK_EX, $status );
1154 if ( !$status->isOK() ) {
1155 wfProfileOut( __METHOD__ . '-' . $this->name );
1156 wfProfileOut( __METHOD__ );
1157 return $status; // abort
1158 }
1159 }
1160
1161 // Clear any file cache entries (after locks acquired)
1162 if ( empty( $opts['preserveCache'] ) ) {
1163 $this->clearCache();
1164 }
1165
1166 // Load from the persistent file and container caches
1167 $this->primeFileCache( $performOps );
1168 $this->primeContainerCache( $performOps );
1169
1170 // Actually attempt the operation batch...
1171 $opts = $this->setConcurrencyFlags( $opts );
1172 $subStatus = FileOpBatch::attempt( $performOps, $opts, $this->fileJournal );
1173
1174 // Merge errors into status fields
1175 $status->merge( $subStatus );
1176 $status->success = $subStatus->success; // not done in merge()
1177
1178 wfProfileOut( __METHOD__ . '-' . $this->name );
1179 wfProfileOut( __METHOD__ );
1180 return $status;
1181 }
1182
1183 /**
1184 * @see FileBackend::doQuickOperationsInternal()
1185 * @return Status
1186 * @throws MWException
1187 */
1188 final protected function doQuickOperationsInternal( array $ops ) {
1189 wfProfileIn( __METHOD__ );
1190 wfProfileIn( __METHOD__ . '-' . $this->name );
1191 $status = Status::newGood();
1192
1193 if ( !count( $ops ) ) {
1194 return $status; // nothing to do
1195 }
1196
1197 // Fix up custom header name/value pairs...
1198 $ops = array_map( array( $this, 'stripInvalidHeadersFromOp' ), $ops );
1199
1200 // Clear any file cache entries
1201 $this->clearCache();
1202
1203 $supportedOps = array( 'create', 'store', 'copy', 'move', 'delete', 'null' );
1204 $async = ( $this->parallelize === 'implicit' );
1205 $maxConcurrency = $this->concurrency; // throttle
1206
1207 $statuses = array(); // array of (index => Status)
1208 $fileOpHandles = array(); // list of (index => handle) arrays
1209 $curFileOpHandles = array(); // current handle batch
1210 // Perform the sync-only ops and build up op handles for the async ops...
1211 foreach ( $ops as $index => $params ) {
1212 if ( !in_array( $params['op'], $supportedOps ) ) {
1213 wfProfileOut( __METHOD__ . '-' . $this->name );
1214 wfProfileOut( __METHOD__ );
1215 throw new MWException( "Operation '{$params['op']}' is not supported." );
1216 }
1217 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1218 $subStatus = $this->$method( array( 'async' => $async ) + $params );
1219 if ( $subStatus->value instanceof FileBackendStoreOpHandle ) { // async
1220 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1221 $fileOpHandles[] = $curFileOpHandles; // push this batch
1222 $curFileOpHandles = array();
1223 }
1224 $curFileOpHandles[$index] = $subStatus->value; // keep index
1225 } else { // error or completed
1226 $statuses[$index] = $subStatus; // keep index
1227 }
1228 }
1229 if ( count( $curFileOpHandles ) ) {
1230 $fileOpHandles[] = $curFileOpHandles; // last batch
1231 }
1232 // Do all the async ops that can be done concurrently...
1233 foreach ( $fileOpHandles as $fileHandleBatch ) {
1234 $statuses = $statuses + $this->executeOpHandlesInternal( $fileHandleBatch );
1235 }
1236 // Marshall and merge all the responses...
1237 foreach ( $statuses as $index => $subStatus ) {
1238 $status->merge( $subStatus );
1239 if ( $subStatus->isOK() ) {
1240 $status->success[$index] = true;
1241 ++$status->successCount;
1242 } else {
1243 $status->success[$index] = false;
1244 ++$status->failCount;
1245 }
1246 }
1247
1248 wfProfileOut( __METHOD__ . '-' . $this->name );
1249 wfProfileOut( __METHOD__ );
1250 return $status;
1251 }
1252
1253 /**
1254 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1255 * The resulting Status object fields will correspond
1256 * to the order in which the handles where given.
1257 *
1258 * @param array $handles List of FileBackendStoreOpHandle objects
1259 * @return Array Map of Status objects
1260 * @throws MWException
1261 */
1262 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1263 wfProfileIn( __METHOD__ );
1264 wfProfileIn( __METHOD__ . '-' . $this->name );
1265 foreach ( $fileOpHandles as $fileOpHandle ) {
1266 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle ) ) {
1267 wfProfileOut( __METHOD__ . '-' . $this->name );
1268 wfProfileOut( __METHOD__ );
1269 throw new MWException( "Given a non-FileBackendStoreOpHandle object." );
1270 } elseif ( $fileOpHandle->backend->getName() !== $this->getName() ) {
1271 wfProfileOut( __METHOD__ . '-' . $this->name );
1272 wfProfileOut( __METHOD__ );
1273 throw new MWException( "Given a FileBackendStoreOpHandle for the wrong backend." );
1274 }
1275 }
1276 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1277 foreach ( $fileOpHandles as $fileOpHandle ) {
1278 $fileOpHandle->closeResources();
1279 }
1280 wfProfileOut( __METHOD__ . '-' . $this->name );
1281 wfProfileOut( __METHOD__ );
1282 return $res;
1283 }
1284
1285 /**
1286 * @see FileBackendStore::executeOpHandlesInternal()
1287 * @param array $fileOpHandles
1288 * @throws MWException
1289 * @return Array List of corresponding Status objects
1290 */
1291 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1292 foreach ( $fileOpHandles as $fileOpHandle ) { // OK if empty
1293 throw new MWException( "This backend supports no asynchronous operations." );
1294 }
1295 return array();
1296 }
1297
1298 /**
1299 * Strip long HTTP headers from a file operation.
1300 * Most headers are just numbers, but some are allowed to be long.
1301 * This function is useful for cleaning up headers and avoiding backend
1302 * specific errors, especially in the middle of batch file operations.
1303 *
1304 * @param array $op Same format as doOperation()
1305 * @return Array
1306 */
1307 protected function stripInvalidHeadersFromOp( array $op ) {
1308 static $longs = array( 'Content-Disposition' );
1309 if ( isset( $op['headers'] ) ) { // op sets HTTP headers
1310 foreach ( $op['headers'] as $name => $value ) {
1311 $maxHVLen = in_array( $name, $longs ) ? INF : 255;
1312 if ( strlen( $name ) > 255 || strlen( $value ) > $maxHVLen ) {
1313 trigger_error( "Header '$name: $value' is too long." );
1314 unset( $op['headers'][$name] );
1315 } elseif ( !strlen( $value ) ) {
1316 $op['headers'][$name] = ''; // null/false => ""
1317 }
1318 }
1319 }
1320 return $op;
1321 }
1322
1323 /**
1324 * @see FileBackend::preloadCache()
1325 */
1326 final public function preloadCache( array $paths ) {
1327 $fullConts = array(); // full container names
1328 foreach ( $paths as $path ) {
1329 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1330 $fullConts[] = $fullCont;
1331 }
1332 // Load from the persistent file and container caches
1333 $this->primeContainerCache( $fullConts );
1334 $this->primeFileCache( $paths );
1335 }
1336
1337 /**
1338 * @see FileBackend::clearCache()
1339 */
1340 final public function clearCache( array $paths = null ) {
1341 if ( is_array( $paths ) ) {
1342 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1343 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1344 }
1345 if ( $paths === null ) {
1346 $this->cheapCache->clear();
1347 $this->expensiveCache->clear();
1348 } else {
1349 foreach ( $paths as $path ) {
1350 $this->cheapCache->clear( $path );
1351 $this->expensiveCache->clear( $path );
1352 }
1353 }
1354 $this->doClearCache( $paths );
1355 }
1356
1357 /**
1358 * Clears any additional stat caches for storage paths
1359 *
1360 * @see FileBackend::clearCache()
1361 *
1362 * @param array $paths Storage paths (optional)
1363 * @return void
1364 */
1365 protected function doClearCache( array $paths = null ) {}
1366
1367 /**
1368 * Is this a key/value store where directories are just virtual?
1369 * Virtual directories exists in so much as files exists that are
1370 * prefixed with the directory path followed by a forward slash.
1371 *
1372 * @return bool
1373 */
1374 abstract protected function directoriesAreVirtual();
1375
1376 /**
1377 * Check if a container name is valid.
1378 * This checks for for length and illegal characters.
1379 *
1380 * @param $container string
1381 * @return bool
1382 */
1383 final protected static function isValidContainerName( $container ) {
1384 // This accounts for Swift and S3 restrictions while leaving room
1385 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1386 // This disallows directory separators or traversal characters.
1387 // Note that matching strings URL encode to the same string;
1388 // in Swift, the length restriction is *after* URL encoding.
1389 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1390 }
1391
1392 /**
1393 * Splits a storage path into an internal container name,
1394 * an internal relative file name, and a container shard suffix.
1395 * Any shard suffix is already appended to the internal container name.
1396 * This also checks that the storage path is valid and within this backend.
1397 *
1398 * If the container is sharded but a suffix could not be determined,
1399 * this means that the path can only refer to a directory and can only
1400 * be scanned by looking in all the container shards.
1401 *
1402 * @param $storagePath string
1403 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1404 */
1405 final protected function resolveStoragePath( $storagePath ) {
1406 list( $backend, $container, $relPath ) = self::splitStoragePath( $storagePath );
1407 if ( $backend === $this->name ) { // must be for this backend
1408 $relPath = self::normalizeContainerPath( $relPath );
1409 if ( $relPath !== null ) {
1410 // Get shard for the normalized path if this container is sharded
1411 $cShard = $this->getContainerShard( $container, $relPath );
1412 // Validate and sanitize the relative path (backend-specific)
1413 $relPath = $this->resolveContainerPath( $container, $relPath );
1414 if ( $relPath !== null ) {
1415 // Prepend any wiki ID prefix to the container name
1416 $container = $this->fullContainerName( $container );
1417 if ( self::isValidContainerName( $container ) ) {
1418 // Validate and sanitize the container name (backend-specific)
1419 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1420 if ( $container !== null ) {
1421 return array( $container, $relPath, $cShard );
1422 }
1423 }
1424 }
1425 }
1426 }
1427 return array( null, null, null );
1428 }
1429
1430 /**
1431 * Like resolveStoragePath() except null values are returned if
1432 * the container is sharded and the shard could not be determined
1433 * or if the path ends with '/'. The later case is illegal for FS
1434 * backends and can confuse listings for object store backends.
1435 *
1436 * This function is used when resolving paths that must be valid
1437 * locations for files. Directory and listing functions should
1438 * generally just use resolveStoragePath() instead.
1439 *
1440 * @see FileBackendStore::resolveStoragePath()
1441 *
1442 * @param $storagePath string
1443 * @return Array (container, path) or (null, null) if invalid
1444 */
1445 final protected function resolveStoragePathReal( $storagePath ) {
1446 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1447 if ( $cShard !== null && substr( $relPath, -1 ) !== '/' ) {
1448 return array( $container, $relPath );
1449 }
1450 return array( null, null );
1451 }
1452
1453 /**
1454 * Get the container name shard suffix for a given path.
1455 * Any empty suffix means the container is not sharded.
1456 *
1457 * @param string $container Container name
1458 * @param string $relPath Storage path relative to the container
1459 * @return string|null Returns null if shard could not be determined
1460 */
1461 final protected function getContainerShard( $container, $relPath ) {
1462 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1463 if ( $levels == 1 || $levels == 2 ) {
1464 // Hash characters are either base 16 or 36
1465 $char = ( $base == 36 ) ? '[0-9a-z]' : '[0-9a-f]';
1466 // Get a regex that represents the shard portion of paths.
1467 // The concatenation of the captures gives us the shard.
1468 if ( $levels === 1 ) { // 16 or 36 shards per container
1469 $hashDirRegex = '(' . $char . ')';
1470 } else { // 256 or 1296 shards per container
1471 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1472 $hashDirRegex = $char . '/(' . $char . '{2})';
1473 } else { // short hash dir format (e.g. "a/b/c")
1474 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1475 }
1476 }
1477 // Allow certain directories to be above the hash dirs so as
1478 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1479 // They must be 2+ chars to avoid any hash directory ambiguity.
1480 $m = array();
1481 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1482 return '.' . implode( '', array_slice( $m, 1 ) );
1483 }
1484 return null; // failed to match
1485 }
1486 return ''; // no sharding
1487 }
1488
1489 /**
1490 * Check if a storage path maps to a single shard.
1491 * Container dirs like "a", where the container shards on "x/xy",
1492 * can reside on several shards. Such paths are tricky to handle.
1493 *
1494 * @param string $storagePath Storage path
1495 * @return bool
1496 */
1497 final public function isSingleShardPathInternal( $storagePath ) {
1498 list( , , $shard ) = $this->resolveStoragePath( $storagePath );
1499 return ( $shard !== null );
1500 }
1501
1502 /**
1503 * Get the sharding config for a container.
1504 * If greater than 0, then all file storage paths within
1505 * the container are required to be hashed accordingly.
1506 *
1507 * @param $container string
1508 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
1509 */
1510 final protected function getContainerHashLevels( $container ) {
1511 if ( isset( $this->shardViaHashLevels[$container] ) ) {
1512 $config = $this->shardViaHashLevels[$container];
1513 $hashLevels = (int)$config['levels'];
1514 if ( $hashLevels == 1 || $hashLevels == 2 ) {
1515 $hashBase = (int)$config['base'];
1516 if ( $hashBase == 16 || $hashBase == 36 ) {
1517 return array( $hashLevels, $hashBase, $config['repeat'] );
1518 }
1519 }
1520 }
1521 return array( 0, 0, false ); // no sharding
1522 }
1523
1524 /**
1525 * Get a list of full container shard suffixes for a container
1526 *
1527 * @param $container string
1528 * @return Array
1529 */
1530 final protected function getContainerSuffixes( $container ) {
1531 $shards = array();
1532 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1533 if ( $digits > 0 ) {
1534 $numShards = pow( $base, $digits );
1535 for ( $index = 0; $index < $numShards; $index++ ) {
1536 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1537 }
1538 }
1539 return $shards;
1540 }
1541
1542 /**
1543 * Get the full container name, including the wiki ID prefix
1544 *
1545 * @param $container string
1546 * @return string
1547 */
1548 final protected function fullContainerName( $container ) {
1549 if ( $this->wikiId != '' ) {
1550 return "{$this->wikiId}-$container";
1551 } else {
1552 return $container;
1553 }
1554 }
1555
1556 /**
1557 * Resolve a container name, checking if it's allowed by the backend.
1558 * This is intended for internal use, such as encoding illegal chars.
1559 * Subclasses can override this to be more restrictive.
1560 *
1561 * @param $container string
1562 * @return string|null
1563 */
1564 protected function resolveContainerName( $container ) {
1565 return $container;
1566 }
1567
1568 /**
1569 * Resolve a relative storage path, checking if it's allowed by the backend.
1570 * This is intended for internal use, such as encoding illegal chars or perhaps
1571 * getting absolute paths (e.g. FS based backends). Note that the relative path
1572 * may be the empty string (e.g. the path is simply to the container).
1573 *
1574 * @param string $container Container name
1575 * @param string $relStoragePath Storage path relative to the container
1576 * @return string|null Path or null if not valid
1577 */
1578 protected function resolveContainerPath( $container, $relStoragePath ) {
1579 return $relStoragePath;
1580 }
1581
1582 /**
1583 * Get the cache key for a container
1584 *
1585 * @param string $container Resolved container name
1586 * @return string
1587 */
1588 private function containerCacheKey( $container ) {
1589 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1590 }
1591
1592 /**
1593 * Set the cached info for a container
1594 *
1595 * @param string $container Resolved container name
1596 * @param array $val Information to cache
1597 * @return void
1598 */
1599 final protected function setContainerCache( $container, array $val ) {
1600 $this->memCache->add( $this->containerCacheKey( $container ), $val, 14 * 86400 );
1601 }
1602
1603 /**
1604 * Delete the cached info for a container.
1605 * The cache key is salted for a while to prevent race conditions.
1606 *
1607 * @param string $container Resolved container name
1608 * @return void
1609 */
1610 final protected function deleteContainerCache( $container ) {
1611 if ( !$this->memCache->set( $this->containerCacheKey( $container ), 'PURGED', 300 ) ) {
1612 trigger_error( "Unable to delete stat cache for container $container." );
1613 }
1614 }
1615
1616 /**
1617 * Do a batch lookup from cache for container stats for all containers
1618 * used in a list of container names, storage paths, or FileOp objects.
1619 * This loads the persistent cache values into the process cache.
1620 *
1621 * @param $items Array
1622 * @return void
1623 */
1624 final protected function primeContainerCache( array $items ) {
1625 wfProfileIn( __METHOD__ );
1626 wfProfileIn( __METHOD__ . '-' . $this->name );
1627
1628 $paths = array(); // list of storage paths
1629 $contNames = array(); // (cache key => resolved container name)
1630 // Get all the paths/containers from the items...
1631 foreach ( $items as $item ) {
1632 if ( $item instanceof FileOp ) {
1633 $paths = array_merge( $paths, $item->storagePathsRead() );
1634 $paths = array_merge( $paths, $item->storagePathsChanged() );
1635 } elseif ( self::isStoragePath( $item ) ) {
1636 $paths[] = $item;
1637 } elseif ( is_string( $item ) ) { // full container name
1638 $contNames[$this->containerCacheKey( $item )] = $item;
1639 }
1640 }
1641 // Get all the corresponding cache keys for paths...
1642 foreach ( $paths as $path ) {
1643 list( $fullCont, , ) = $this->resolveStoragePath( $path );
1644 if ( $fullCont !== null ) { // valid path for this backend
1645 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1646 }
1647 }
1648
1649 $contInfo = array(); // (resolved container name => cache value)
1650 // Get all cache entries for these container cache keys...
1651 $values = $this->memCache->getMulti( array_keys( $contNames ) );
1652 foreach ( $values as $cacheKey => $val ) {
1653 $contInfo[$contNames[$cacheKey]] = $val;
1654 }
1655
1656 // Populate the container process cache for the backend...
1657 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1658
1659 wfProfileOut( __METHOD__ . '-' . $this->name );
1660 wfProfileOut( __METHOD__ );
1661 }
1662
1663 /**
1664 * Fill the backend-specific process cache given an array of
1665 * resolved container names and their corresponding cached info.
1666 * Only containers that actually exist should appear in the map.
1667 *
1668 * @param array $containerInfo Map of resolved container names to cached info
1669 * @return void
1670 */
1671 protected function doPrimeContainerCache( array $containerInfo ) {}
1672
1673 /**
1674 * Get the cache key for a file path
1675 *
1676 * @param string $path Normalized storage path
1677 * @return string
1678 */
1679 private function fileCacheKey( $path ) {
1680 return wfMemcKey( 'backend', $this->getName(), 'file', sha1( $path ) );
1681 }
1682
1683 /**
1684 * Set the cached stat info for a file path.
1685 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1686 * salting for the case when a file is created at a path were there was none before.
1687 *
1688 * @param string $path Storage path
1689 * @param array $val Stat information to cache
1690 * @return void
1691 */
1692 final protected function setFileCache( $path, array $val ) {
1693 $path = FileBackend::normalizeStoragePath( $path );
1694 if ( $path === null ) {
1695 return; // invalid storage path
1696 }
1697 $age = time() - wfTimestamp( TS_UNIX, $val['mtime'] );
1698 $ttl = min( 7 * 86400, max( 300, floor( .1 * $age ) ) );
1699 $this->memCache->add( $this->fileCacheKey( $path ), $val, $ttl );
1700 }
1701
1702 /**
1703 * Delete the cached stat info for a file path.
1704 * The cache key is salted for a while to prevent race conditions.
1705 * Since negatives (404s) are not cached, this does not need to be called when
1706 * a file is created at a path were there was none before.
1707 *
1708 * @param string $path Storage path
1709 * @return void
1710 */
1711 final protected function deleteFileCache( $path ) {
1712 $path = FileBackend::normalizeStoragePath( $path );
1713 if ( $path === null ) {
1714 return; // invalid storage path
1715 }
1716 if ( !$this->memCache->set( $this->fileCacheKey( $path ), 'PURGED', 300 ) ) {
1717 trigger_error( "Unable to delete stat cache for file $path." );
1718 }
1719 }
1720
1721 /**
1722 * Do a batch lookup from cache for file stats for all paths
1723 * used in a list of storage paths or FileOp objects.
1724 * This loads the persistent cache values into the process cache.
1725 *
1726 * @param array $items List of storage paths or FileOps
1727 * @return void
1728 */
1729 final protected function primeFileCache( array $items ) {
1730 wfProfileIn( __METHOD__ );
1731 wfProfileIn( __METHOD__ . '-' . $this->name );
1732
1733 $paths = array(); // list of storage paths
1734 $pathNames = array(); // (cache key => storage path)
1735 // Get all the paths/containers from the items...
1736 foreach ( $items as $item ) {
1737 if ( $item instanceof FileOp ) {
1738 $paths = array_merge( $paths, $item->storagePathsRead() );
1739 $paths = array_merge( $paths, $item->storagePathsChanged() );
1740 } elseif ( self::isStoragePath( $item ) ) {
1741 $paths[] = FileBackend::normalizeStoragePath( $item );
1742 }
1743 }
1744 // Get rid of any paths that failed normalization...
1745 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1746 // Get all the corresponding cache keys for paths...
1747 foreach ( $paths as $path ) {
1748 list( , $rel, ) = $this->resolveStoragePath( $path );
1749 if ( $rel !== null ) { // valid path for this backend
1750 $pathNames[$this->fileCacheKey( $path )] = $path;
1751 }
1752 }
1753 // Get all cache entries for these container cache keys...
1754 $values = $this->memCache->getMulti( array_keys( $pathNames ) );
1755 foreach ( $values as $cacheKey => $val ) {
1756 if ( is_array( $val ) ) {
1757 $path = $pathNames[$cacheKey];
1758 $this->cheapCache->set( $path, 'stat', $val );
1759 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1760 $this->cheapCache->set( $path, 'sha1',
1761 array( 'hash' => $val['sha1'], 'latest' => $val['latest'] ) );
1762 }
1763 }
1764 }
1765
1766 wfProfileOut( __METHOD__ . '-' . $this->name );
1767 wfProfileOut( __METHOD__ );
1768 }
1769
1770 /**
1771 * Set the 'concurrency' option from a list of operation options
1772 *
1773 * @param array $opts Map of operation options
1774 * @return Array
1775 */
1776 final protected function setConcurrencyFlags( array $opts ) {
1777 $opts['concurrency'] = 1; // off
1778 if ( $this->parallelize === 'implicit' ) {
1779 if ( !isset( $opts['parallelize'] ) || $opts['parallelize'] ) {
1780 $opts['concurrency'] = $this->concurrency;
1781 }
1782 } elseif ( $this->parallelize === 'explicit' ) {
1783 if ( !empty( $opts['parallelize'] ) ) {
1784 $opts['concurrency'] = $this->concurrency;
1785 }
1786 }
1787 return $opts;
1788 }
1789 }
1790
1791 /**
1792 * FileBackendStore helper class for performing asynchronous file operations.
1793 *
1794 * For example, calling FileBackendStore::createInternal() with the "async"
1795 * param flag may result in a Status that contains this object as a value.
1796 * This class is largely backend-specific and is mostly just "magic" to be
1797 * passed to FileBackendStore::executeOpHandlesInternal().
1798 */
1799 abstract class FileBackendStoreOpHandle {
1800 /** @var Array */
1801 public $params = array(); // params to caller functions
1802 /** @var FileBackendStore */
1803 public $backend;
1804 /** @var Array */
1805 public $resourcesToClose = array();
1806
1807 public $call; // string; name that identifies the function called
1808
1809 /**
1810 * Close all open file handles
1811 *
1812 * @return void
1813 */
1814 public function closeResources() {
1815 array_map( 'fclose', $this->resourcesToClose );
1816 }
1817 }
1818
1819 /**
1820 * FileBackendStore helper function to handle listings that span container shards.
1821 * Do not use this class from places outside of FileBackendStore.
1822 *
1823 * @ingroup FileBackend
1824 */
1825 abstract class FileBackendStoreShardListIterator extends FilterIterator {
1826 /** @var FileBackendStore */
1827 protected $backend;
1828 /** @var Array */
1829 protected $params;
1830
1831 protected $container; // string; full container name
1832 protected $directory; // string; resolved relative path
1833
1834 /** @var Array */
1835 protected $multiShardPaths = array(); // (rel path => 1)
1836
1837 /**
1838 * @param $backend FileBackendStore
1839 * @param string $container Full storage container name
1840 * @param string $dir Storage directory relative to container
1841 * @param array $suffixes List of container shard suffixes
1842 * @param array $params
1843 */
1844 public function __construct(
1845 FileBackendStore $backend, $container, $dir, array $suffixes, array $params
1846 ) {
1847 $this->backend = $backend;
1848 $this->container = $container;
1849 $this->directory = $dir;
1850 $this->params = $params;
1851
1852 $iter = new AppendIterator();
1853 foreach ( $suffixes as $suffix ) {
1854 $iter->append( $this->listFromShard( $this->container . $suffix ) );
1855 }
1856
1857 parent::__construct( $iter );
1858 }
1859
1860 public function accept() {
1861 $rel = $this->getInnerIterator()->current(); // path relative to given directory
1862 $path = $this->params['dir'] . "/{$rel}"; // full storage path
1863 if ( $this->backend->isSingleShardPathInternal( $path ) ) {
1864 return true; // path is only on one shard; no issue with duplicates
1865 } elseif ( isset( $this->multiShardPaths[$rel] ) ) {
1866 // Don't keep listing paths that are on multiple shards
1867 return false;
1868 } else {
1869 $this->multiShardPaths[$rel] = 1;
1870 return true;
1871 }
1872 }
1873
1874 public function rewind() {
1875 parent::rewind();
1876 $this->multiShardPaths = array();
1877 }
1878
1879 /**
1880 * Get the list for a given container shard
1881 *
1882 * @param string $container Resolved container name
1883 * @return Iterator
1884 */
1885 abstract protected function listFromShard( $container );
1886 }
1887
1888 /**
1889 * Iterator for listing directories
1890 */
1891 class FileBackendStoreShardDirIterator extends FileBackendStoreShardListIterator {
1892 protected function listFromShard( $container ) {
1893 $list = $this->backend->getDirectoryListInternal(
1894 $container, $this->directory, $this->params );
1895 if ( $list === null ) {
1896 return new ArrayIterator( array() );
1897 } else {
1898 return is_array( $list ) ? new ArrayIterator( $list ) : $list;
1899 }
1900 }
1901 }
1902
1903 /**
1904 * Iterator for listing regular files
1905 */
1906 class FileBackendStoreShardFileIterator extends FileBackendStoreShardListIterator {
1907 protected function listFromShard( $container ) {
1908 $list = $this->backend->getFileListInternal(
1909 $container, $this->directory, $this->params );
1910 if ( $list === null ) {
1911 return new ArrayIterator( array() );
1912 } else {
1913 return is_array( $list ) ? new ArrayIterator( $list ) : $list;
1914 }
1915 }
1916 }