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