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