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