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