Merge "Various javascript optimizations (fixes bug 39959)"
[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(), 'r' );
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::getLocalReference()
724 * @return TempFSFile|null
725 */
726 public function getLocalReference( array $params ) {
727 $path = self::normalizeStoragePath( $params['src'] );
728 if ( $path === null ) {
729 return null; // invalid storage path
730 }
731 wfProfileIn( __METHOD__ );
732 wfProfileIn( __METHOD__ . '-' . $this->name );
733 $latest = !empty( $params['latest'] ); // use latest data?
734 if ( $this->expensiveCache->has( $path, 'localRef' ) ) {
735 $val = $this->expensiveCache->get( $path, 'localRef' );
736 // If we want the latest data, check that this cached
737 // value was in fact fetched with the latest available data.
738 if ( !$latest || $val['latest'] ) {
739 wfProfileOut( __METHOD__ . '-' . $this->name );
740 wfProfileOut( __METHOD__ );
741 return $val['object'];
742 }
743 }
744 $tmpFile = $this->getLocalCopy( $params );
745 if ( $tmpFile ) { // don't cache negatives
746 $this->expensiveCache->set( $path, 'localRef',
747 array( 'object' => $tmpFile, 'latest' => $latest ) );
748 }
749 wfProfileOut( __METHOD__ . '-' . $this->name );
750 wfProfileOut( __METHOD__ );
751 return $tmpFile;
752 }
753
754 /**
755 * @see FileBackend::streamFile()
756 * @return Status
757 */
758 final public function streamFile( array $params ) {
759 wfProfileIn( __METHOD__ );
760 wfProfileIn( __METHOD__ . '-' . $this->name );
761 $status = Status::newGood();
762
763 $info = $this->getFileStat( $params );
764 if ( !$info ) { // let StreamFile handle the 404
765 $status->fatal( 'backend-fail-notexists', $params['src'] );
766 }
767
768 // Set output buffer and HTTP headers for stream
769 $extraHeaders = isset( $params['headers'] ) ? $params['headers'] : array();
770 $res = StreamFile::prepareForStream( $params['src'], $info, $extraHeaders );
771 if ( $res == StreamFile::NOT_MODIFIED ) {
772 // do nothing; client cache is up to date
773 } elseif ( $res == StreamFile::READY_STREAM ) {
774 wfProfileIn( __METHOD__ . '-send' );
775 wfProfileIn( __METHOD__ . '-send-' . $this->name );
776 $status = $this->doStreamFile( $params );
777 wfProfileOut( __METHOD__ . '-send-' . $this->name );
778 wfProfileOut( __METHOD__ . '-send' );
779 } else {
780 $status->fatal( 'backend-fail-stream', $params['src'] );
781 }
782
783 wfProfileOut( __METHOD__ . '-' . $this->name );
784 wfProfileOut( __METHOD__ );
785 return $status;
786 }
787
788 /**
789 * @see FileBackendStore::streamFile()
790 * @return Status
791 */
792 protected function doStreamFile( array $params ) {
793 $status = Status::newGood();
794
795 $fsFile = $this->getLocalReference( $params );
796 if ( !$fsFile ) {
797 $status->fatal( 'backend-fail-stream', $params['src'] );
798 } elseif ( !readfile( $fsFile->getPath() ) ) {
799 $status->fatal( 'backend-fail-stream', $params['src'] );
800 }
801
802 return $status;
803 }
804
805 /**
806 * @see FileBackend::directoryExists()
807 * @return bool|null
808 */
809 final public function directoryExists( array $params ) {
810 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
811 if ( $dir === null ) {
812 return false; // invalid storage path
813 }
814 if ( $shard !== null ) { // confined to a single container/shard
815 return $this->doDirectoryExists( $fullCont, $dir, $params );
816 } else { // directory is on several shards
817 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
818 list( $b, $shortCont, $r ) = self::splitStoragePath( $params['dir'] );
819 $res = false; // response
820 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
821 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
822 if ( $exists ) {
823 $res = true;
824 break; // found one!
825 } elseif ( $exists === null ) { // error?
826 $res = null; // if we don't find anything, it is indeterminate
827 }
828 }
829 return $res;
830 }
831 }
832
833 /**
834 * @see FileBackendStore::directoryExists()
835 *
836 * @param $container string Resolved container name
837 * @param $dir string Resolved path relative to container
838 * @param $params Array
839 * @return bool|null
840 */
841 abstract protected function doDirectoryExists( $container, $dir, array $params );
842
843 /**
844 * @see FileBackend::getDirectoryList()
845 * @return Traversable|Array|null Returns null on failure
846 */
847 final public function getDirectoryList( array $params ) {
848 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
849 if ( $dir === null ) { // invalid storage path
850 return null;
851 }
852 if ( $shard !== null ) {
853 // File listing is confined to a single container/shard
854 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
855 } else {
856 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
857 // File listing spans multiple containers/shards
858 list( $b, $shortCont, $r ) = self::splitStoragePath( $params['dir'] );
859 return new FileBackendStoreShardDirIterator( $this,
860 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
861 }
862 }
863
864 /**
865 * Do not call this function from places outside FileBackend
866 *
867 * @see FileBackendStore::getDirectoryList()
868 *
869 * @param $container string Resolved container name
870 * @param $dir string Resolved path relative to container
871 * @param $params Array
872 * @return Traversable|Array|null Returns null on failure
873 */
874 abstract public function getDirectoryListInternal( $container, $dir, array $params );
875
876 /**
877 * @see FileBackend::getFileList()
878 * @return Traversable|Array|null Returns null on failure
879 */
880 final public function getFileList( array $params ) {
881 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
882 if ( $dir === null ) { // invalid storage path
883 return null;
884 }
885 if ( $shard !== null ) {
886 // File listing is confined to a single container/shard
887 return $this->getFileListInternal( $fullCont, $dir, $params );
888 } else {
889 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
890 // File listing spans multiple containers/shards
891 list( $b, $shortCont, $r ) = self::splitStoragePath( $params['dir'] );
892 return new FileBackendStoreShardFileIterator( $this,
893 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
894 }
895 }
896
897 /**
898 * Do not call this function from places outside FileBackend
899 *
900 * @see FileBackendStore::getFileList()
901 *
902 * @param $container string Resolved container name
903 * @param $dir string Resolved path relative to container
904 * @param $params Array
905 * @return Traversable|Array|null Returns null on failure
906 */
907 abstract public function getFileListInternal( $container, $dir, array $params );
908
909 /**
910 * Return a list of FileOp objects from a list of operations.
911 * Do not call this function from places outside FileBackend.
912 *
913 * The result must have the same number of items as the input.
914 * An exception is thrown if an unsupported operation is requested.
915 *
916 * @param $ops Array Same format as doOperations()
917 * @return Array List of FileOp objects
918 * @throws MWException
919 */
920 final public function getOperationsInternal( array $ops ) {
921 $supportedOps = array(
922 'store' => 'StoreFileOp',
923 'copy' => 'CopyFileOp',
924 'move' => 'MoveFileOp',
925 'delete' => 'DeleteFileOp',
926 'create' => 'CreateFileOp',
927 'null' => 'NullFileOp'
928 );
929
930 $performOps = array(); // array of FileOp objects
931 // Build up ordered array of FileOps...
932 foreach ( $ops as $operation ) {
933 $opName = $operation['op'];
934 if ( isset( $supportedOps[$opName] ) ) {
935 $class = $supportedOps[$opName];
936 // Get params for this operation
937 $params = $operation;
938 // Append the FileOp class
939 $performOps[] = new $class( $this, $params );
940 } else {
941 throw new MWException( "Operation '$opName' is not supported." );
942 }
943 }
944
945 return $performOps;
946 }
947
948 /**
949 * Get a list of storage paths to lock for a list of operations
950 * Returns an array with 'sh' (shared) and 'ex' (exclusive) keys,
951 * each corresponding to a list of storage paths to be locked.
952 *
953 * @param $performOps Array List of FileOp objects
954 * @return Array ('sh' => list of paths, 'ex' => list of paths)
955 */
956 final public function getPathsToLockForOpsInternal( array $performOps ) {
957 // Build up a list of files to lock...
958 $paths = array( 'sh' => array(), 'ex' => array() );
959 foreach ( $performOps as $fileOp ) {
960 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
961 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
962 }
963 // Optimization: if doing an EX lock anyway, don't also set an SH one
964 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
965 // Get a shared lock on the parent directory of each path changed
966 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
967
968 return $paths;
969 }
970
971 /**
972 * @see FileBackend::getScopedLocksForOps()
973 * @return Array
974 */
975 public function getScopedLocksForOps( array $ops, Status $status ) {
976 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
977 return array(
978 $this->getScopedFileLocks( $paths['sh'], LockManager::LOCK_UW, $status ),
979 $this->getScopedFileLocks( $paths['ex'], LockManager::LOCK_EX, $status )
980 );
981 }
982
983 /**
984 * @see FileBackend::doOperationsInternal()
985 * @return Status
986 */
987 final protected function doOperationsInternal( array $ops, array $opts ) {
988 wfProfileIn( __METHOD__ );
989 wfProfileIn( __METHOD__ . '-' . $this->name );
990 $status = Status::newGood();
991
992 // Build up a list of FileOps...
993 $performOps = $this->getOperationsInternal( $ops );
994
995 // Acquire any locks as needed...
996 if ( empty( $opts['nonLocking'] ) ) {
997 // Build up a list of files to lock...
998 $paths = $this->getPathsToLockForOpsInternal( $performOps );
999 // Try to lock those files for the scope of this function...
1000 $scopeLockS = $this->getScopedFileLocks( $paths['sh'], LockManager::LOCK_UW, $status );
1001 $scopeLockE = $this->getScopedFileLocks( $paths['ex'], LockManager::LOCK_EX, $status );
1002 if ( !$status->isOK() ) {
1003 wfProfileOut( __METHOD__ . '-' . $this->name );
1004 wfProfileOut( __METHOD__ );
1005 return $status; // abort
1006 }
1007 }
1008
1009 // Clear any file cache entries (after locks acquired)
1010 if ( empty( $opts['preserveCache'] ) ) {
1011 $this->clearCache();
1012 }
1013
1014 // Load from the persistent file and container caches
1015 $this->primeFileCache( $performOps );
1016 $this->primeContainerCache( $performOps );
1017
1018 // Actually attempt the operation batch...
1019 $subStatus = FileOpBatch::attempt( $performOps, $opts, $this->fileJournal );
1020
1021 // Merge errors into status fields
1022 $status->merge( $subStatus );
1023 $status->success = $subStatus->success; // not done in merge()
1024
1025 wfProfileOut( __METHOD__ . '-' . $this->name );
1026 wfProfileOut( __METHOD__ );
1027 return $status;
1028 }
1029
1030 /**
1031 * @see FileBackend::doQuickOperationsInternal()
1032 * @return Status
1033 * @throws MWException
1034 */
1035 final protected function doQuickOperationsInternal( array $ops ) {
1036 wfProfileIn( __METHOD__ );
1037 wfProfileIn( __METHOD__ . '-' . $this->name );
1038 $status = Status::newGood();
1039
1040 $supportedOps = array( 'create', 'store', 'copy', 'move', 'delete', 'null' );
1041 $async = ( $this->parallelize === 'implicit' );
1042 $maxConcurrency = $this->concurrency; // throttle
1043
1044 $statuses = array(); // array of (index => Status)
1045 $fileOpHandles = array(); // list of (index => handle) arrays
1046 $curFileOpHandles = array(); // current handle batch
1047 // Perform the sync-only ops and build up op handles for the async ops...
1048 foreach ( $ops as $index => $params ) {
1049 if ( !in_array( $params['op'], $supportedOps ) ) {
1050 wfProfileOut( __METHOD__ . '-' . $this->name );
1051 wfProfileOut( __METHOD__ );
1052 throw new MWException( "Operation '{$params['op']}' is not supported." );
1053 }
1054 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1055 $subStatus = $this->$method( array( 'async' => $async ) + $params );
1056 if ( $subStatus->value instanceof FileBackendStoreOpHandle ) { // async
1057 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1058 $fileOpHandles[] = $curFileOpHandles; // push this batch
1059 $curFileOpHandles = array();
1060 }
1061 $curFileOpHandles[$index] = $subStatus->value; // keep index
1062 } else { // error or completed
1063 $statuses[$index] = $subStatus; // keep index
1064 }
1065 }
1066 if ( count( $curFileOpHandles ) ) {
1067 $fileOpHandles[] = $curFileOpHandles; // last batch
1068 }
1069 // Do all the async ops that can be done concurrently...
1070 foreach ( $fileOpHandles as $fileHandleBatch ) {
1071 $statuses = $statuses + $this->executeOpHandlesInternal( $fileHandleBatch );
1072 }
1073 // Marshall and merge all the responses...
1074 foreach ( $statuses as $index => $subStatus ) {
1075 $status->merge( $subStatus );
1076 if ( $subStatus->isOK() ) {
1077 $status->success[$index] = true;
1078 ++$status->successCount;
1079 } else {
1080 $status->success[$index] = false;
1081 ++$status->failCount;
1082 }
1083 }
1084
1085 wfProfileOut( __METHOD__ . '-' . $this->name );
1086 wfProfileOut( __METHOD__ );
1087 return $status;
1088 }
1089
1090 /**
1091 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1092 * The resulting Status object fields will correspond
1093 * to the order in which the handles where given.
1094 *
1095 * @param $handles Array List of FileBackendStoreOpHandle objects
1096 * @return Array Map of Status objects
1097 * @throws MWException
1098 */
1099 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1100 wfProfileIn( __METHOD__ );
1101 wfProfileIn( __METHOD__ . '-' . $this->name );
1102 foreach ( $fileOpHandles as $fileOpHandle ) {
1103 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle ) ) {
1104 throw new MWException( "Given a non-FileBackendStoreOpHandle object." );
1105 } elseif ( $fileOpHandle->backend->getName() !== $this->getName() ) {
1106 throw new MWException( "Given a FileBackendStoreOpHandle for the wrong backend." );
1107 }
1108 }
1109 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1110 foreach ( $fileOpHandles as $fileOpHandle ) {
1111 $fileOpHandle->closeResources();
1112 }
1113 wfProfileOut( __METHOD__ . '-' . $this->name );
1114 wfProfileOut( __METHOD__ );
1115 return $res;
1116 }
1117
1118 /**
1119 * @see FileBackendStore::executeOpHandlesInternal()
1120 * @return Array List of corresponding Status objects
1121 */
1122 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1123 foreach ( $fileOpHandles as $fileOpHandle ) { // OK if empty
1124 throw new MWException( "This backend supports no asynchronous operations." );
1125 }
1126 return array();
1127 }
1128
1129 /**
1130 * @see FileBackend::preloadCache()
1131 */
1132 final public function preloadCache( array $paths ) {
1133 $fullConts = array(); // full container names
1134 foreach ( $paths as $path ) {
1135 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1136 $fullConts[] = $fullCont;
1137 }
1138 // Load from the persistent file and container caches
1139 $this->primeContainerCache( $fullConts );
1140 $this->primeFileCache( $paths );
1141 }
1142
1143 /**
1144 * @see FileBackend::clearCache()
1145 */
1146 final public function clearCache( array $paths = null ) {
1147 if ( is_array( $paths ) ) {
1148 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1149 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1150 }
1151 if ( $paths === null ) {
1152 $this->cheapCache->clear();
1153 $this->expensiveCache->clear();
1154 } else {
1155 foreach ( $paths as $path ) {
1156 $this->cheapCache->clear( $path );
1157 $this->expensiveCache->clear( $path );
1158 }
1159 }
1160 $this->doClearCache( $paths );
1161 }
1162
1163 /**
1164 * Clears any additional stat caches for storage paths
1165 *
1166 * @see FileBackend::clearCache()
1167 *
1168 * @param $paths Array Storage paths (optional)
1169 * @return void
1170 */
1171 protected function doClearCache( array $paths = null ) {}
1172
1173 /**
1174 * Is this a key/value store where directories are just virtual?
1175 * Virtual directories exists in so much as files exists that are
1176 * prefixed with the directory path followed by a forward slash.
1177 *
1178 * @return bool
1179 */
1180 abstract protected function directoriesAreVirtual();
1181
1182 /**
1183 * Check if a container name is valid.
1184 * This checks for for length and illegal characters.
1185 *
1186 * @param $container string
1187 * @return bool
1188 */
1189 final protected static function isValidContainerName( $container ) {
1190 // This accounts for Swift and S3 restrictions while leaving room
1191 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1192 // This disallows directory separators or traversal characters.
1193 // Note that matching strings URL encode to the same string;
1194 // in Swift, the length restriction is *after* URL encoding.
1195 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1196 }
1197
1198 /**
1199 * Splits a storage path into an internal container name,
1200 * an internal relative file name, and a container shard suffix.
1201 * Any shard suffix is already appended to the internal container name.
1202 * This also checks that the storage path is valid and within this backend.
1203 *
1204 * If the container is sharded but a suffix could not be determined,
1205 * this means that the path can only refer to a directory and can only
1206 * be scanned by looking in all the container shards.
1207 *
1208 * @param $storagePath string
1209 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1210 */
1211 final protected function resolveStoragePath( $storagePath ) {
1212 list( $backend, $container, $relPath ) = self::splitStoragePath( $storagePath );
1213 if ( $backend === $this->name ) { // must be for this backend
1214 $relPath = self::normalizeContainerPath( $relPath );
1215 if ( $relPath !== null ) {
1216 // Get shard for the normalized path if this container is sharded
1217 $cShard = $this->getContainerShard( $container, $relPath );
1218 // Validate and sanitize the relative path (backend-specific)
1219 $relPath = $this->resolveContainerPath( $container, $relPath );
1220 if ( $relPath !== null ) {
1221 // Prepend any wiki ID prefix to the container name
1222 $container = $this->fullContainerName( $container );
1223 if ( self::isValidContainerName( $container ) ) {
1224 // Validate and sanitize the container name (backend-specific)
1225 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1226 if ( $container !== null ) {
1227 return array( $container, $relPath, $cShard );
1228 }
1229 }
1230 }
1231 }
1232 }
1233 return array( null, null, null );
1234 }
1235
1236 /**
1237 * Like resolveStoragePath() except null values are returned if
1238 * the container is sharded and the shard could not be determined.
1239 *
1240 * @see FileBackendStore::resolveStoragePath()
1241 *
1242 * @param $storagePath string
1243 * @return Array (container, path) or (null, null) if invalid
1244 */
1245 final protected function resolveStoragePathReal( $storagePath ) {
1246 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1247 if ( $cShard !== null ) {
1248 return array( $container, $relPath );
1249 }
1250 return array( null, null );
1251 }
1252
1253 /**
1254 * Get the container name shard suffix for a given path.
1255 * Any empty suffix means the container is not sharded.
1256 *
1257 * @param $container string Container name
1258 * @param $relPath string Storage path relative to the container
1259 * @return string|null Returns null if shard could not be determined
1260 */
1261 final protected function getContainerShard( $container, $relPath ) {
1262 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1263 if ( $levels == 1 || $levels == 2 ) {
1264 // Hash characters are either base 16 or 36
1265 $char = ( $base == 36 ) ? '[0-9a-z]' : '[0-9a-f]';
1266 // Get a regex that represents the shard portion of paths.
1267 // The concatenation of the captures gives us the shard.
1268 if ( $levels === 1 ) { // 16 or 36 shards per container
1269 $hashDirRegex = '(' . $char . ')';
1270 } else { // 256 or 1296 shards per container
1271 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1272 $hashDirRegex = $char . '/(' . $char . '{2})';
1273 } else { // short hash dir format (e.g. "a/b/c")
1274 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1275 }
1276 }
1277 // Allow certain directories to be above the hash dirs so as
1278 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1279 // They must be 2+ chars to avoid any hash directory ambiguity.
1280 $m = array();
1281 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1282 return '.' . implode( '', array_slice( $m, 1 ) );
1283 }
1284 return null; // failed to match
1285 }
1286 return ''; // no sharding
1287 }
1288
1289 /**
1290 * Check if a storage path maps to a single shard.
1291 * Container dirs like "a", where the container shards on "x/xy",
1292 * can reside on several shards. Such paths are tricky to handle.
1293 *
1294 * @param $storagePath string Storage path
1295 * @return bool
1296 */
1297 final public function isSingleShardPathInternal( $storagePath ) {
1298 list( $c, $r, $shard ) = $this->resolveStoragePath( $storagePath );
1299 return ( $shard !== null );
1300 }
1301
1302 /**
1303 * Get the sharding config for a container.
1304 * If greater than 0, then all file storage paths within
1305 * the container are required to be hashed accordingly.
1306 *
1307 * @param $container string
1308 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
1309 */
1310 final protected function getContainerHashLevels( $container ) {
1311 if ( isset( $this->shardViaHashLevels[$container] ) ) {
1312 $config = $this->shardViaHashLevels[$container];
1313 $hashLevels = (int)$config['levels'];
1314 if ( $hashLevels == 1 || $hashLevels == 2 ) {
1315 $hashBase = (int)$config['base'];
1316 if ( $hashBase == 16 || $hashBase == 36 ) {
1317 return array( $hashLevels, $hashBase, $config['repeat'] );
1318 }
1319 }
1320 }
1321 return array( 0, 0, false ); // no sharding
1322 }
1323
1324 /**
1325 * Get a list of full container shard suffixes for a container
1326 *
1327 * @param $container string
1328 * @return Array
1329 */
1330 final protected function getContainerSuffixes( $container ) {
1331 $shards = array();
1332 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1333 if ( $digits > 0 ) {
1334 $numShards = pow( $base, $digits );
1335 for ( $index = 0; $index < $numShards; $index++ ) {
1336 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1337 }
1338 }
1339 return $shards;
1340 }
1341
1342 /**
1343 * Get the full container name, including the wiki ID prefix
1344 *
1345 * @param $container string
1346 * @return string
1347 */
1348 final protected function fullContainerName( $container ) {
1349 if ( $this->wikiId != '' ) {
1350 return "{$this->wikiId}-$container";
1351 } else {
1352 return $container;
1353 }
1354 }
1355
1356 /**
1357 * Resolve a container name, checking if it's allowed by the backend.
1358 * This is intended for internal use, such as encoding illegal chars.
1359 * Subclasses can override this to be more restrictive.
1360 *
1361 * @param $container string
1362 * @return string|null
1363 */
1364 protected function resolveContainerName( $container ) {
1365 return $container;
1366 }
1367
1368 /**
1369 * Resolve a relative storage path, checking if it's allowed by the backend.
1370 * This is intended for internal use, such as encoding illegal chars or perhaps
1371 * getting absolute paths (e.g. FS based backends). Note that the relative path
1372 * may be the empty string (e.g. the path is simply to the container).
1373 *
1374 * @param $container string Container name
1375 * @param $relStoragePath string Storage path relative to the container
1376 * @return string|null Path or null if not valid
1377 */
1378 protected function resolveContainerPath( $container, $relStoragePath ) {
1379 return $relStoragePath;
1380 }
1381
1382 /**
1383 * Get the cache key for a container
1384 *
1385 * @param $container string Resolved container name
1386 * @return string
1387 */
1388 private function containerCacheKey( $container ) {
1389 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1390 }
1391
1392 /**
1393 * Set the cached info for a container
1394 *
1395 * @param $container string Resolved container name
1396 * @param $val mixed Information to cache
1397 */
1398 final protected function setContainerCache( $container, $val ) {
1399 $this->memCache->add( $this->containerCacheKey( $container ), $val, 14*86400 );
1400 }
1401
1402 /**
1403 * Delete the cached info for a container.
1404 * The cache key is salted for a while to prevent race conditions.
1405 *
1406 * @param $container string Resolved container name
1407 */
1408 final protected function deleteContainerCache( $container ) {
1409 if ( !$this->memCache->set( $this->containerCacheKey( $container ), 'PURGED', 300 ) ) {
1410 trigger_error( "Unable to delete stat cache for container $container." );
1411 }
1412 }
1413
1414 /**
1415 * Do a batch lookup from cache for container stats for all containers
1416 * used in a list of container names, storage paths, or FileOp objects.
1417 *
1418 * @param $items Array
1419 * @return void
1420 */
1421 final protected function primeContainerCache( array $items ) {
1422 wfProfileIn( __METHOD__ );
1423 wfProfileIn( __METHOD__ . '-' . $this->name );
1424
1425 $paths = array(); // list of storage paths
1426 $contNames = array(); // (cache key => resolved container name)
1427 // Get all the paths/containers from the items...
1428 foreach ( $items as $item ) {
1429 if ( $item instanceof FileOp ) {
1430 $paths = array_merge( $paths, $item->storagePathsRead() );
1431 $paths = array_merge( $paths, $item->storagePathsChanged() );
1432 } elseif ( self::isStoragePath( $item ) ) {
1433 $paths[] = $item;
1434 } elseif ( is_string( $item ) ) { // full container name
1435 $contNames[$this->containerCacheKey( $item )] = $item;
1436 }
1437 }
1438 // Get all the corresponding cache keys for paths...
1439 foreach ( $paths as $path ) {
1440 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1441 if ( $fullCont !== null ) { // valid path for this backend
1442 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1443 }
1444 }
1445
1446 $contInfo = array(); // (resolved container name => cache value)
1447 // Get all cache entries for these container cache keys...
1448 $values = $this->memCache->getMulti( array_keys( $contNames ) );
1449 foreach ( $values as $cacheKey => $val ) {
1450 $contInfo[$contNames[$cacheKey]] = $val;
1451 }
1452
1453 // Populate the container process cache for the backend...
1454 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1455
1456 wfProfileOut( __METHOD__ . '-' . $this->name );
1457 wfProfileOut( __METHOD__ );
1458 }
1459
1460 /**
1461 * Fill the backend-specific process cache given an array of
1462 * resolved container names and their corresponding cached info.
1463 * Only containers that actually exist should appear in the map.
1464 *
1465 * @param $containerInfo Array Map of resolved container names to cached info
1466 * @return void
1467 */
1468 protected function doPrimeContainerCache( array $containerInfo ) {}
1469
1470 /**
1471 * Get the cache key for a file path
1472 *
1473 * @param $path string Storage path
1474 * @return string
1475 */
1476 private function fileCacheKey( $path ) {
1477 return wfMemcKey( 'backend', $this->getName(), 'file', sha1( $path ) );
1478 }
1479
1480 /**
1481 * Set the cached stat info for a file path.
1482 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1483 * salting for the case when a file is created at a path were there was none before.
1484 *
1485 * @param $path string Storage path
1486 * @param $val mixed Information to cache
1487 */
1488 final protected function setFileCache( $path, $val ) {
1489 $this->memCache->add( $this->fileCacheKey( $path ), $val, 7*86400 );
1490 }
1491
1492 /**
1493 * Delete the cached stat info for a file path.
1494 * The cache key is salted for a while to prevent race conditions.
1495 *
1496 * @param $path string Storage path
1497 */
1498 final protected function deleteFileCache( $path ) {
1499 if ( !$this->memCache->set( $this->fileCacheKey( $path ), 'PURGED', 300 ) ) {
1500 trigger_error( "Unable to delete stat cache for file $path." );
1501 }
1502 }
1503
1504 /**
1505 * Do a batch lookup from cache for file stats for all paths
1506 * used in a list of storage paths or FileOp objects.
1507 *
1508 * @param $items Array List of storage paths or FileOps
1509 * @return void
1510 */
1511 final protected function primeFileCache( array $items ) {
1512 wfProfileIn( __METHOD__ );
1513 wfProfileIn( __METHOD__ . '-' . $this->name );
1514
1515 $paths = array(); // list of storage paths
1516 $pathNames = array(); // (cache key => storage path)
1517 // Get all the paths/containers from the items...
1518 foreach ( $items as $item ) {
1519 if ( $item instanceof FileOp ) {
1520 $paths = array_merge( $paths, $item->storagePathsRead() );
1521 $paths = array_merge( $paths, $item->storagePathsChanged() );
1522 } elseif ( self::isStoragePath( $item ) ) {
1523 $paths[] = $item;
1524 }
1525 }
1526 // Get all the corresponding cache keys for paths...
1527 foreach ( $paths as $path ) {
1528 list( $cont, $rel, $s ) = $this->resolveStoragePath( $path );
1529 if ( $rel !== null ) { // valid path for this backend
1530 $pathNames[$this->fileCacheKey( $path )] = $path;
1531 }
1532 }
1533 // Get all cache entries for these container cache keys...
1534 $values = $this->memCache->getMulti( array_keys( $pathNames ) );
1535 foreach ( $values as $cacheKey => $val ) {
1536 if ( is_array( $val ) ) {
1537 $path = $pathNames[$cacheKey];
1538 $this->cheapCache->set( $path, 'stat', $val );
1539 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1540 $this->cheapCache->set( $path, 'sha1',
1541 array( 'hash' => $val['sha1'], 'latest' => $val['latest'] ) );
1542 }
1543 }
1544 }
1545
1546 wfProfileOut( __METHOD__ . '-' . $this->name );
1547 wfProfileOut( __METHOD__ );
1548 }
1549 }
1550
1551 /**
1552 * FileBackendStore helper class for performing asynchronous file operations.
1553 *
1554 * For example, calling FileBackendStore::createInternal() with the "async"
1555 * param flag may result in a Status that contains this object as a value.
1556 * This class is largely backend-specific and is mostly just "magic" to be
1557 * passed to FileBackendStore::executeOpHandlesInternal().
1558 */
1559 abstract class FileBackendStoreOpHandle {
1560 /** @var Array */
1561 public $params = array(); // params to caller functions
1562 /** @var FileBackendStore */
1563 public $backend;
1564 /** @var Array */
1565 public $resourcesToClose = array();
1566
1567 public $call; // string; name that identifies the function called
1568
1569 /**
1570 * Close all open file handles
1571 *
1572 * @return void
1573 */
1574 public function closeResources() {
1575 array_map( 'fclose', $this->resourcesToClose );
1576 }
1577 }
1578
1579 /**
1580 * FileBackendStore helper function to handle listings that span container shards.
1581 * Do not use this class from places outside of FileBackendStore.
1582 *
1583 * @ingroup FileBackend
1584 */
1585 abstract class FileBackendStoreShardListIterator implements Iterator {
1586 /** @var FileBackendStore */
1587 protected $backend;
1588 /** @var Array */
1589 protected $params;
1590 /** @var Array */
1591 protected $shardSuffixes;
1592 protected $container; // string; full container name
1593 protected $directory; // string; resolved relative path
1594
1595 /** @var Traversable */
1596 protected $iter;
1597 protected $curShard = 0; // integer
1598 protected $pos = 0; // integer
1599
1600 /** @var Array */
1601 protected $multiShardPaths = array(); // (rel path => 1)
1602
1603 /**
1604 * @param $backend FileBackendStore
1605 * @param $container string Full storage container name
1606 * @param $dir string Storage directory relative to container
1607 * @param $suffixes Array List of container shard suffixes
1608 * @param $params Array
1609 */
1610 public function __construct(
1611 FileBackendStore $backend, $container, $dir, array $suffixes, array $params
1612 ) {
1613 $this->backend = $backend;
1614 $this->container = $container;
1615 $this->directory = $dir;
1616 $this->shardSuffixes = $suffixes;
1617 $this->params = $params;
1618 }
1619
1620 /**
1621 * @see Iterator::key()
1622 * @return integer
1623 */
1624 public function key() {
1625 return $this->pos;
1626 }
1627
1628 /**
1629 * @see Iterator::valid()
1630 * @return bool
1631 */
1632 public function valid() {
1633 if ( $this->iter instanceof Iterator ) {
1634 return $this->iter->valid();
1635 } elseif ( is_array( $this->iter ) ) {
1636 return ( current( $this->iter ) !== false ); // no paths can have this value
1637 }
1638 return false; // some failure?
1639 }
1640
1641 /**
1642 * @see Iterator::current()
1643 * @return string|bool String or false
1644 */
1645 public function current() {
1646 return ( $this->iter instanceof Iterator )
1647 ? $this->iter->current()
1648 : current( $this->iter );
1649 }
1650
1651 /**
1652 * @see Iterator::next()
1653 * @return void
1654 */
1655 public function next() {
1656 ++$this->pos;
1657 ( $this->iter instanceof Iterator ) ? $this->iter->next() : next( $this->iter );
1658 do {
1659 $continue = false; // keep scanning shards?
1660 $this->filterViaNext(); // filter out duplicates
1661 // Find the next non-empty shard if no elements are left
1662 if ( !$this->valid() ) {
1663 $this->nextShardIteratorIfNotValid();
1664 $continue = $this->valid(); // re-filter unless we ran out of shards
1665 }
1666 } while ( $continue );
1667 }
1668
1669 /**
1670 * @see Iterator::rewind()
1671 * @return void
1672 */
1673 public function rewind() {
1674 $this->pos = 0;
1675 $this->curShard = 0;
1676 $this->setIteratorFromCurrentShard();
1677 do {
1678 $continue = false; // keep scanning shards?
1679 $this->filterViaNext(); // filter out duplicates
1680 // Find the next non-empty shard if no elements are left
1681 if ( !$this->valid() ) {
1682 $this->nextShardIteratorIfNotValid();
1683 $continue = $this->valid(); // re-filter unless we ran out of shards
1684 }
1685 } while ( $continue );
1686 }
1687
1688 /**
1689 * Filter out duplicate items by advancing to the next ones
1690 */
1691 protected function filterViaNext() {
1692 while ( $this->valid() ) {
1693 $rel = $this->iter->current(); // path relative to given directory
1694 $path = $this->params['dir'] . "/{$rel}"; // full storage path
1695 if ( $this->backend->isSingleShardPathInternal( $path ) ) {
1696 break; // path is only on one shard; no issue with duplicates
1697 } elseif ( isset( $this->multiShardPaths[$rel] ) ) {
1698 // Don't keep listing paths that are on multiple shards
1699 ( $this->iter instanceof Iterator ) ? $this->iter->next() : next( $this->iter );
1700 } else {
1701 $this->multiShardPaths[$rel] = 1;
1702 break;
1703 }
1704 }
1705 }
1706
1707 /**
1708 * If the list iterator for this container shard is out of items,
1709 * then move on to the next container that has items.
1710 * If there are none, then it advances to the last container.
1711 */
1712 protected function nextShardIteratorIfNotValid() {
1713 while ( !$this->valid() && ++$this->curShard < count( $this->shardSuffixes ) ) {
1714 $this->setIteratorFromCurrentShard();
1715 }
1716 }
1717
1718 /**
1719 * Set the list iterator to that of the current container shard
1720 */
1721 protected function setIteratorFromCurrentShard() {
1722 $this->iter = $this->listFromShard(
1723 $this->container . $this->shardSuffixes[$this->curShard],
1724 $this->directory, $this->params );
1725 // Start loading results so that current() works
1726 if ( $this->iter ) {
1727 ( $this->iter instanceof Iterator ) ? $this->iter->rewind() : reset( $this->iter );
1728 }
1729 }
1730
1731 /**
1732 * Get the list for a given container shard
1733 *
1734 * @param $container string Resolved container name
1735 * @param $dir string Resolved path relative to container
1736 * @param $params Array
1737 * @return Traversable|Array|null
1738 */
1739 abstract protected function listFromShard( $container, $dir, array $params );
1740 }
1741
1742 /**
1743 * Iterator for listing directories
1744 */
1745 class FileBackendStoreShardDirIterator extends FileBackendStoreShardListIterator {
1746 /**
1747 * @see FileBackendStoreShardListIterator::listFromShard()
1748 * @return Array|null|Traversable
1749 */
1750 protected function listFromShard( $container, $dir, array $params ) {
1751 return $this->backend->getDirectoryListInternal( $container, $dir, $params );
1752 }
1753 }
1754
1755 /**
1756 * Iterator for listing regular files
1757 */
1758 class FileBackendStoreShardFileIterator extends FileBackendStoreShardListIterator {
1759 /**
1760 * @see FileBackendStoreShardListIterator::listFromShard()
1761 * @return Array|null|Traversable
1762 */
1763 protected function listFromShard( $container, $dir, array $params ) {
1764 return $this->backend->getFileListInternal( $container, $dir, $params );
1765 }
1766 }