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