Merge "Added protocol option to Linker and OutputPage::addReturnTo."
[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 $opts = $this->setConcurrencyFlags( $opts );
1020 $subStatus = FileOpBatch::attempt( $performOps, $opts, $this->fileJournal );
1021
1022 // Merge errors into status fields
1023 $status->merge( $subStatus );
1024 $status->success = $subStatus->success; // not done in merge()
1025
1026 wfProfileOut( __METHOD__ . '-' . $this->name );
1027 wfProfileOut( __METHOD__ );
1028 return $status;
1029 }
1030
1031 /**
1032 * @see FileBackend::doQuickOperationsInternal()
1033 * @return Status
1034 * @throws MWException
1035 */
1036 final protected function doQuickOperationsInternal( array $ops ) {
1037 wfProfileIn( __METHOD__ );
1038 wfProfileIn( __METHOD__ . '-' . $this->name );
1039 $status = Status::newGood();
1040
1041 $supportedOps = array( 'create', 'store', 'copy', 'move', 'delete', 'null' );
1042 $async = ( $this->parallelize === 'implicit' );
1043 $maxConcurrency = $this->concurrency; // throttle
1044
1045 $statuses = array(); // array of (index => Status)
1046 $fileOpHandles = array(); // list of (index => handle) arrays
1047 $curFileOpHandles = array(); // current handle batch
1048 // Perform the sync-only ops and build up op handles for the async ops...
1049 foreach ( $ops as $index => $params ) {
1050 if ( !in_array( $params['op'], $supportedOps ) ) {
1051 wfProfileOut( __METHOD__ . '-' . $this->name );
1052 wfProfileOut( __METHOD__ );
1053 throw new MWException( "Operation '{$params['op']}' is not supported." );
1054 }
1055 $method = $params['op'] . 'Internal'; // e.g. "storeInternal"
1056 $subStatus = $this->$method( array( 'async' => $async ) + $params );
1057 if ( $subStatus->value instanceof FileBackendStoreOpHandle ) { // async
1058 if ( count( $curFileOpHandles ) >= $maxConcurrency ) {
1059 $fileOpHandles[] = $curFileOpHandles; // push this batch
1060 $curFileOpHandles = array();
1061 }
1062 $curFileOpHandles[$index] = $subStatus->value; // keep index
1063 } else { // error or completed
1064 $statuses[$index] = $subStatus; // keep index
1065 }
1066 }
1067 if ( count( $curFileOpHandles ) ) {
1068 $fileOpHandles[] = $curFileOpHandles; // last batch
1069 }
1070 // Do all the async ops that can be done concurrently...
1071 foreach ( $fileOpHandles as $fileHandleBatch ) {
1072 $statuses = $statuses + $this->executeOpHandlesInternal( $fileHandleBatch );
1073 }
1074 // Marshall and merge all the responses...
1075 foreach ( $statuses as $index => $subStatus ) {
1076 $status->merge( $subStatus );
1077 if ( $subStatus->isOK() ) {
1078 $status->success[$index] = true;
1079 ++$status->successCount;
1080 } else {
1081 $status->success[$index] = false;
1082 ++$status->failCount;
1083 }
1084 }
1085
1086 wfProfileOut( __METHOD__ . '-' . $this->name );
1087 wfProfileOut( __METHOD__ );
1088 return $status;
1089 }
1090
1091 /**
1092 * Execute a list of FileBackendStoreOpHandle handles in parallel.
1093 * The resulting Status object fields will correspond
1094 * to the order in which the handles where given.
1095 *
1096 * @param $handles Array List of FileBackendStoreOpHandle objects
1097 * @return Array Map of Status objects
1098 * @throws MWException
1099 */
1100 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1101 wfProfileIn( __METHOD__ );
1102 wfProfileIn( __METHOD__ . '-' . $this->name );
1103 foreach ( $fileOpHandles as $fileOpHandle ) {
1104 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle ) ) {
1105 throw new MWException( "Given a non-FileBackendStoreOpHandle object." );
1106 } elseif ( $fileOpHandle->backend->getName() !== $this->getName() ) {
1107 throw new MWException( "Given a FileBackendStoreOpHandle for the wrong backend." );
1108 }
1109 }
1110 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1111 foreach ( $fileOpHandles as $fileOpHandle ) {
1112 $fileOpHandle->closeResources();
1113 }
1114 wfProfileOut( __METHOD__ . '-' . $this->name );
1115 wfProfileOut( __METHOD__ );
1116 return $res;
1117 }
1118
1119 /**
1120 * @see FileBackendStore::executeOpHandlesInternal()
1121 * @return Array List of corresponding Status objects
1122 */
1123 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1124 foreach ( $fileOpHandles as $fileOpHandle ) { // OK if empty
1125 throw new MWException( "This backend supports no asynchronous operations." );
1126 }
1127 return array();
1128 }
1129
1130 /**
1131 * @see FileBackend::preloadCache()
1132 */
1133 final public function preloadCache( array $paths ) {
1134 $fullConts = array(); // full container names
1135 foreach ( $paths as $path ) {
1136 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1137 $fullConts[] = $fullCont;
1138 }
1139 // Load from the persistent file and container caches
1140 $this->primeContainerCache( $fullConts );
1141 $this->primeFileCache( $paths );
1142 }
1143
1144 /**
1145 * @see FileBackend::clearCache()
1146 */
1147 final public function clearCache( array $paths = null ) {
1148 if ( is_array( $paths ) ) {
1149 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1150 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1151 }
1152 if ( $paths === null ) {
1153 $this->cheapCache->clear();
1154 $this->expensiveCache->clear();
1155 } else {
1156 foreach ( $paths as $path ) {
1157 $this->cheapCache->clear( $path );
1158 $this->expensiveCache->clear( $path );
1159 }
1160 }
1161 $this->doClearCache( $paths );
1162 }
1163
1164 /**
1165 * Clears any additional stat caches for storage paths
1166 *
1167 * @see FileBackend::clearCache()
1168 *
1169 * @param $paths Array Storage paths (optional)
1170 * @return void
1171 */
1172 protected function doClearCache( array $paths = null ) {}
1173
1174 /**
1175 * Is this a key/value store where directories are just virtual?
1176 * Virtual directories exists in so much as files exists that are
1177 * prefixed with the directory path followed by a forward slash.
1178 *
1179 * @return bool
1180 */
1181 abstract protected function directoriesAreVirtual();
1182
1183 /**
1184 * Check if a container name is valid.
1185 * This checks for for length and illegal characters.
1186 *
1187 * @param $container string
1188 * @return bool
1189 */
1190 final protected static function isValidContainerName( $container ) {
1191 // This accounts for Swift and S3 restrictions while leaving room
1192 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1193 // This disallows directory separators or traversal characters.
1194 // Note that matching strings URL encode to the same string;
1195 // in Swift, the length restriction is *after* URL encoding.
1196 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1197 }
1198
1199 /**
1200 * Splits a storage path into an internal container name,
1201 * an internal relative file name, and a container shard suffix.
1202 * Any shard suffix is already appended to the internal container name.
1203 * This also checks that the storage path is valid and within this backend.
1204 *
1205 * If the container is sharded but a suffix could not be determined,
1206 * this means that the path can only refer to a directory and can only
1207 * be scanned by looking in all the container shards.
1208 *
1209 * @param $storagePath string
1210 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1211 */
1212 final protected function resolveStoragePath( $storagePath ) {
1213 list( $backend, $container, $relPath ) = self::splitStoragePath( $storagePath );
1214 if ( $backend === $this->name ) { // must be for this backend
1215 $relPath = self::normalizeContainerPath( $relPath );
1216 if ( $relPath !== null ) {
1217 // Get shard for the normalized path if this container is sharded
1218 $cShard = $this->getContainerShard( $container, $relPath );
1219 // Validate and sanitize the relative path (backend-specific)
1220 $relPath = $this->resolveContainerPath( $container, $relPath );
1221 if ( $relPath !== null ) {
1222 // Prepend any wiki ID prefix to the container name
1223 $container = $this->fullContainerName( $container );
1224 if ( self::isValidContainerName( $container ) ) {
1225 // Validate and sanitize the container name (backend-specific)
1226 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1227 if ( $container !== null ) {
1228 return array( $container, $relPath, $cShard );
1229 }
1230 }
1231 }
1232 }
1233 }
1234 return array( null, null, null );
1235 }
1236
1237 /**
1238 * Like resolveStoragePath() except null values are returned if
1239 * the container is sharded and the shard could not be determined.
1240 *
1241 * @see FileBackendStore::resolveStoragePath()
1242 *
1243 * @param $storagePath string
1244 * @return Array (container, path) or (null, null) if invalid
1245 */
1246 final protected function resolveStoragePathReal( $storagePath ) {
1247 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1248 if ( $cShard !== null ) {
1249 return array( $container, $relPath );
1250 }
1251 return array( null, null );
1252 }
1253
1254 /**
1255 * Get the container name shard suffix for a given path.
1256 * Any empty suffix means the container is not sharded.
1257 *
1258 * @param $container string Container name
1259 * @param $relPath string Storage path relative to the container
1260 * @return string|null Returns null if shard could not be determined
1261 */
1262 final protected function getContainerShard( $container, $relPath ) {
1263 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1264 if ( $levels == 1 || $levels == 2 ) {
1265 // Hash characters are either base 16 or 36
1266 $char = ( $base == 36 ) ? '[0-9a-z]' : '[0-9a-f]';
1267 // Get a regex that represents the shard portion of paths.
1268 // The concatenation of the captures gives us the shard.
1269 if ( $levels === 1 ) { // 16 or 36 shards per container
1270 $hashDirRegex = '(' . $char . ')';
1271 } else { // 256 or 1296 shards per container
1272 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1273 $hashDirRegex = $char . '/(' . $char . '{2})';
1274 } else { // short hash dir format (e.g. "a/b/c")
1275 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1276 }
1277 }
1278 // Allow certain directories to be above the hash dirs so as
1279 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1280 // They must be 2+ chars to avoid any hash directory ambiguity.
1281 $m = array();
1282 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1283 return '.' . implode( '', array_slice( $m, 1 ) );
1284 }
1285 return null; // failed to match
1286 }
1287 return ''; // no sharding
1288 }
1289
1290 /**
1291 * Check if a storage path maps to a single shard.
1292 * Container dirs like "a", where the container shards on "x/xy",
1293 * can reside on several shards. Such paths are tricky to handle.
1294 *
1295 * @param $storagePath string Storage path
1296 * @return bool
1297 */
1298 final public function isSingleShardPathInternal( $storagePath ) {
1299 list( $c, $r, $shard ) = $this->resolveStoragePath( $storagePath );
1300 return ( $shard !== null );
1301 }
1302
1303 /**
1304 * Get the sharding config for a container.
1305 * If greater than 0, then all file storage paths within
1306 * the container are required to be hashed accordingly.
1307 *
1308 * @param $container string
1309 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
1310 */
1311 final protected function getContainerHashLevels( $container ) {
1312 if ( isset( $this->shardViaHashLevels[$container] ) ) {
1313 $config = $this->shardViaHashLevels[$container];
1314 $hashLevels = (int)$config['levels'];
1315 if ( $hashLevels == 1 || $hashLevels == 2 ) {
1316 $hashBase = (int)$config['base'];
1317 if ( $hashBase == 16 || $hashBase == 36 ) {
1318 return array( $hashLevels, $hashBase, $config['repeat'] );
1319 }
1320 }
1321 }
1322 return array( 0, 0, false ); // no sharding
1323 }
1324
1325 /**
1326 * Get a list of full container shard suffixes for a container
1327 *
1328 * @param $container string
1329 * @return Array
1330 */
1331 final protected function getContainerSuffixes( $container ) {
1332 $shards = array();
1333 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1334 if ( $digits > 0 ) {
1335 $numShards = pow( $base, $digits );
1336 for ( $index = 0; $index < $numShards; $index++ ) {
1337 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1338 }
1339 }
1340 return $shards;
1341 }
1342
1343 /**
1344 * Get the full container name, including the wiki ID prefix
1345 *
1346 * @param $container string
1347 * @return string
1348 */
1349 final protected function fullContainerName( $container ) {
1350 if ( $this->wikiId != '' ) {
1351 return "{$this->wikiId}-$container";
1352 } else {
1353 return $container;
1354 }
1355 }
1356
1357 /**
1358 * Resolve a container name, checking if it's allowed by the backend.
1359 * This is intended for internal use, such as encoding illegal chars.
1360 * Subclasses can override this to be more restrictive.
1361 *
1362 * @param $container string
1363 * @return string|null
1364 */
1365 protected function resolveContainerName( $container ) {
1366 return $container;
1367 }
1368
1369 /**
1370 * Resolve a relative storage path, checking if it's allowed by the backend.
1371 * This is intended for internal use, such as encoding illegal chars or perhaps
1372 * getting absolute paths (e.g. FS based backends). Note that the relative path
1373 * may be the empty string (e.g. the path is simply to the container).
1374 *
1375 * @param $container string Container name
1376 * @param $relStoragePath string Storage path relative to the container
1377 * @return string|null Path or null if not valid
1378 */
1379 protected function resolveContainerPath( $container, $relStoragePath ) {
1380 return $relStoragePath;
1381 }
1382
1383 /**
1384 * Get the cache key for a container
1385 *
1386 * @param $container string Resolved container name
1387 * @return string
1388 */
1389 private function containerCacheKey( $container ) {
1390 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1391 }
1392
1393 /**
1394 * Set the cached info for a container
1395 *
1396 * @param $container string Resolved container name
1397 * @param $val mixed Information to cache
1398 */
1399 final protected function setContainerCache( $container, $val ) {
1400 $this->memCache->add( $this->containerCacheKey( $container ), $val, 14*86400 );
1401 }
1402
1403 /**
1404 * Delete the cached info for a container.
1405 * The cache key is salted for a while to prevent race conditions.
1406 *
1407 * @param $container string Resolved container name
1408 */
1409 final protected function deleteContainerCache( $container ) {
1410 if ( !$this->memCache->set( $this->containerCacheKey( $container ), 'PURGED', 300 ) ) {
1411 trigger_error( "Unable to delete stat cache for container $container." );
1412 }
1413 }
1414
1415 /**
1416 * Do a batch lookup from cache for container stats for all containers
1417 * used in a list of container names, storage paths, or FileOp objects.
1418 *
1419 * @param $items Array
1420 * @return void
1421 */
1422 final protected function primeContainerCache( array $items ) {
1423 wfProfileIn( __METHOD__ );
1424 wfProfileIn( __METHOD__ . '-' . $this->name );
1425
1426 $paths = array(); // list of storage paths
1427 $contNames = array(); // (cache key => resolved container name)
1428 // Get all the paths/containers from the items...
1429 foreach ( $items as $item ) {
1430 if ( $item instanceof FileOp ) {
1431 $paths = array_merge( $paths, $item->storagePathsRead() );
1432 $paths = array_merge( $paths, $item->storagePathsChanged() );
1433 } elseif ( self::isStoragePath( $item ) ) {
1434 $paths[] = $item;
1435 } elseif ( is_string( $item ) ) { // full container name
1436 $contNames[$this->containerCacheKey( $item )] = $item;
1437 }
1438 }
1439 // Get all the corresponding cache keys for paths...
1440 foreach ( $paths as $path ) {
1441 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1442 if ( $fullCont !== null ) { // valid path for this backend
1443 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1444 }
1445 }
1446
1447 $contInfo = array(); // (resolved container name => cache value)
1448 // Get all cache entries for these container cache keys...
1449 $values = $this->memCache->getMulti( array_keys( $contNames ) );
1450 foreach ( $values as $cacheKey => $val ) {
1451 $contInfo[$contNames[$cacheKey]] = $val;
1452 }
1453
1454 // Populate the container process cache for the backend...
1455 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1456
1457 wfProfileOut( __METHOD__ . '-' . $this->name );
1458 wfProfileOut( __METHOD__ );
1459 }
1460
1461 /**
1462 * Fill the backend-specific process cache given an array of
1463 * resolved container names and their corresponding cached info.
1464 * Only containers that actually exist should appear in the map.
1465 *
1466 * @param $containerInfo Array Map of resolved container names to cached info
1467 * @return void
1468 */
1469 protected function doPrimeContainerCache( array $containerInfo ) {}
1470
1471 /**
1472 * Get the cache key for a file path
1473 *
1474 * @param $path string Storage path
1475 * @return string
1476 */
1477 private function fileCacheKey( $path ) {
1478 return wfMemcKey( 'backend', $this->getName(), 'file', sha1( $path ) );
1479 }
1480
1481 /**
1482 * Set the cached stat info for a file path.
1483 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1484 * salting for the case when a file is created at a path were there was none before.
1485 *
1486 * @param $path string Storage path
1487 * @param $val mixed Information to cache
1488 */
1489 final protected function setFileCache( $path, $val ) {
1490 $this->memCache->add( $this->fileCacheKey( $path ), $val, 7*86400 );
1491 }
1492
1493 /**
1494 * Delete the cached stat info for a file path.
1495 * The cache key is salted for a while to prevent race conditions.
1496 *
1497 * @param $path string Storage path
1498 */
1499 final protected function deleteFileCache( $path ) {
1500 if ( !$this->memCache->set( $this->fileCacheKey( $path ), 'PURGED', 300 ) ) {
1501 trigger_error( "Unable to delete stat cache for file $path." );
1502 }
1503 }
1504
1505 /**
1506 * Do a batch lookup from cache for file stats for all paths
1507 * used in a list of storage paths or FileOp objects.
1508 *
1509 * @param $items Array List of storage paths or FileOps
1510 * @return void
1511 */
1512 final protected function primeFileCache( array $items ) {
1513 wfProfileIn( __METHOD__ );
1514 wfProfileIn( __METHOD__ . '-' . $this->name );
1515
1516 $paths = array(); // list of storage paths
1517 $pathNames = array(); // (cache key => storage path)
1518 // Get all the paths/containers from the items...
1519 foreach ( $items as $item ) {
1520 if ( $item instanceof FileOp ) {
1521 $paths = array_merge( $paths, $item->storagePathsRead() );
1522 $paths = array_merge( $paths, $item->storagePathsChanged() );
1523 } elseif ( self::isStoragePath( $item ) ) {
1524 $paths[] = $item;
1525 }
1526 }
1527 // Get all the corresponding cache keys for paths...
1528 foreach ( $paths as $path ) {
1529 list( $cont, $rel, $s ) = $this->resolveStoragePath( $path );
1530 if ( $rel !== null ) { // valid path for this backend
1531 $pathNames[$this->fileCacheKey( $path )] = $path;
1532 }
1533 }
1534 // Get all cache entries for these container cache keys...
1535 $values = $this->memCache->getMulti( array_keys( $pathNames ) );
1536 foreach ( $values as $cacheKey => $val ) {
1537 if ( is_array( $val ) ) {
1538 $path = $pathNames[$cacheKey];
1539 $this->cheapCache->set( $path, 'stat', $val );
1540 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1541 $this->cheapCache->set( $path, 'sha1',
1542 array( 'hash' => $val['sha1'], 'latest' => $val['latest'] ) );
1543 }
1544 }
1545 }
1546
1547 wfProfileOut( __METHOD__ . '-' . $this->name );
1548 wfProfileOut( __METHOD__ );
1549 }
1550
1551 /**
1552 * Set the 'concurrency' option from a list of operation options
1553 *
1554 * @param $opts array Map of operation options
1555 * @return Array
1556 */
1557 final protected function setConcurrencyFlags( array $opts ) {
1558 $opts['concurrency'] = 1; // off
1559 if ( $this->parallelize === 'implicit' ) {
1560 if ( !isset( $opts['parallelize'] ) || $opts['parallelize'] ) {
1561 $opts['concurrency'] = $this->concurrency;
1562 }
1563 } elseif ( $this->parallelize === 'explicit' ) {
1564 if ( !empty( $opts['parallelize'] ) ) {
1565 $opts['concurrency'] = $this->concurrency;
1566 }
1567 }
1568 return $opts;
1569 }
1570 }
1571
1572 /**
1573 * FileBackendStore helper class for performing asynchronous file operations.
1574 *
1575 * For example, calling FileBackendStore::createInternal() with the "async"
1576 * param flag may result in a Status that contains this object as a value.
1577 * This class is largely backend-specific and is mostly just "magic" to be
1578 * passed to FileBackendStore::executeOpHandlesInternal().
1579 */
1580 abstract class FileBackendStoreOpHandle {
1581 /** @var Array */
1582 public $params = array(); // params to caller functions
1583 /** @var FileBackendStore */
1584 public $backend;
1585 /** @var Array */
1586 public $resourcesToClose = array();
1587
1588 public $call; // string; name that identifies the function called
1589
1590 /**
1591 * Close all open file handles
1592 *
1593 * @return void
1594 */
1595 public function closeResources() {
1596 array_map( 'fclose', $this->resourcesToClose );
1597 }
1598 }
1599
1600 /**
1601 * FileBackendStore helper function to handle listings that span container shards.
1602 * Do not use this class from places outside of FileBackendStore.
1603 *
1604 * @ingroup FileBackend
1605 */
1606 abstract class FileBackendStoreShardListIterator implements Iterator {
1607 /** @var FileBackendStore */
1608 protected $backend;
1609 /** @var Array */
1610 protected $params;
1611 /** @var Array */
1612 protected $shardSuffixes;
1613 protected $container; // string; full container name
1614 protected $directory; // string; resolved relative path
1615
1616 /** @var Traversable */
1617 protected $iter;
1618 protected $curShard = 0; // integer
1619 protected $pos = 0; // integer
1620
1621 /** @var Array */
1622 protected $multiShardPaths = array(); // (rel path => 1)
1623
1624 /**
1625 * @param $backend FileBackendStore
1626 * @param $container string Full storage container name
1627 * @param $dir string Storage directory relative to container
1628 * @param $suffixes Array List of container shard suffixes
1629 * @param $params Array
1630 */
1631 public function __construct(
1632 FileBackendStore $backend, $container, $dir, array $suffixes, array $params
1633 ) {
1634 $this->backend = $backend;
1635 $this->container = $container;
1636 $this->directory = $dir;
1637 $this->shardSuffixes = $suffixes;
1638 $this->params = $params;
1639 }
1640
1641 /**
1642 * @see Iterator::key()
1643 * @return integer
1644 */
1645 public function key() {
1646 return $this->pos;
1647 }
1648
1649 /**
1650 * @see Iterator::valid()
1651 * @return bool
1652 */
1653 public function valid() {
1654 if ( $this->iter instanceof Iterator ) {
1655 return $this->iter->valid();
1656 } elseif ( is_array( $this->iter ) ) {
1657 return ( current( $this->iter ) !== false ); // no paths can have this value
1658 }
1659 return false; // some failure?
1660 }
1661
1662 /**
1663 * @see Iterator::current()
1664 * @return string|bool String or false
1665 */
1666 public function current() {
1667 return ( $this->iter instanceof Iterator )
1668 ? $this->iter->current()
1669 : current( $this->iter );
1670 }
1671
1672 /**
1673 * @see Iterator::next()
1674 * @return void
1675 */
1676 public function next() {
1677 ++$this->pos;
1678 ( $this->iter instanceof Iterator ) ? $this->iter->next() : next( $this->iter );
1679 do {
1680 $continue = false; // keep scanning shards?
1681 $this->filterViaNext(); // filter out duplicates
1682 // Find the next non-empty shard if no elements are left
1683 if ( !$this->valid() ) {
1684 $this->nextShardIteratorIfNotValid();
1685 $continue = $this->valid(); // re-filter unless we ran out of shards
1686 }
1687 } while ( $continue );
1688 }
1689
1690 /**
1691 * @see Iterator::rewind()
1692 * @return void
1693 */
1694 public function rewind() {
1695 $this->pos = 0;
1696 $this->curShard = 0;
1697 $this->setIteratorFromCurrentShard();
1698 do {
1699 $continue = false; // keep scanning shards?
1700 $this->filterViaNext(); // filter out duplicates
1701 // Find the next non-empty shard if no elements are left
1702 if ( !$this->valid() ) {
1703 $this->nextShardIteratorIfNotValid();
1704 $continue = $this->valid(); // re-filter unless we ran out of shards
1705 }
1706 } while ( $continue );
1707 }
1708
1709 /**
1710 * Filter out duplicate items by advancing to the next ones
1711 */
1712 protected function filterViaNext() {
1713 while ( $this->valid() ) {
1714 $rel = $this->iter->current(); // path relative to given directory
1715 $path = $this->params['dir'] . "/{$rel}"; // full storage path
1716 if ( $this->backend->isSingleShardPathInternal( $path ) ) {
1717 break; // path is only on one shard; no issue with duplicates
1718 } elseif ( isset( $this->multiShardPaths[$rel] ) ) {
1719 // Don't keep listing paths that are on multiple shards
1720 ( $this->iter instanceof Iterator ) ? $this->iter->next() : next( $this->iter );
1721 } else {
1722 $this->multiShardPaths[$rel] = 1;
1723 break;
1724 }
1725 }
1726 }
1727
1728 /**
1729 * If the list iterator for this container shard is out of items,
1730 * then move on to the next container that has items.
1731 * If there are none, then it advances to the last container.
1732 */
1733 protected function nextShardIteratorIfNotValid() {
1734 while ( !$this->valid() && ++$this->curShard < count( $this->shardSuffixes ) ) {
1735 $this->setIteratorFromCurrentShard();
1736 }
1737 }
1738
1739 /**
1740 * Set the list iterator to that of the current container shard
1741 */
1742 protected function setIteratorFromCurrentShard() {
1743 $this->iter = $this->listFromShard(
1744 $this->container . $this->shardSuffixes[$this->curShard],
1745 $this->directory, $this->params );
1746 // Start loading results so that current() works
1747 if ( $this->iter ) {
1748 ( $this->iter instanceof Iterator ) ? $this->iter->rewind() : reset( $this->iter );
1749 }
1750 }
1751
1752 /**
1753 * Get the list for a given container shard
1754 *
1755 * @param $container string Resolved container name
1756 * @param $dir string Resolved path relative to container
1757 * @param $params Array
1758 * @return Traversable|Array|null
1759 */
1760 abstract protected function listFromShard( $container, $dir, array $params );
1761 }
1762
1763 /**
1764 * Iterator for listing directories
1765 */
1766 class FileBackendStoreShardDirIterator extends FileBackendStoreShardListIterator {
1767 /**
1768 * @see FileBackendStoreShardListIterator::listFromShard()
1769 * @return Array|null|Traversable
1770 */
1771 protected function listFromShard( $container, $dir, array $params ) {
1772 return $this->backend->getDirectoryListInternal( $container, $dir, $params );
1773 }
1774 }
1775
1776 /**
1777 * Iterator for listing regular files
1778 */
1779 class FileBackendStoreShardFileIterator extends FileBackendStoreShardListIterator {
1780 /**
1781 * @see FileBackendStoreShardListIterator::listFromShard()
1782 * @return Array|null|Traversable
1783 */
1784 protected function listFromShard( $container, $dir, array $params ) {
1785 return $this->backend->getFileListInternal( $container, $dir, $params );
1786 }
1787 }