[FileBackend] Added container stat caching to reduce RTTs to high latency backends.
[lhc/web/wiklou.git] / includes / filerepo / backend / FileBackendStore.php
1 <?php
2 /**
3 * @file
4 * @ingroup FileBackend
5 * @author Aaron Schulz
6 */
7
8 /**
9 * @brief Base class for all backends using particular storage medium.
10 *
11 * This class defines the methods as abstract that subclasses must implement.
12 * Outside callers should *not* use functions with "Internal" in the name.
13 *
14 * The FileBackend operations are implemented using basic functions
15 * such as storeInternal(), copyInternal(), deleteInternal() and the like.
16 * This class is also responsible for path resolution and sanitization.
17 *
18 * @ingroup FileBackend
19 * @since 1.19
20 */
21 abstract class FileBackendStore extends FileBackend {
22 /** @var BagOStuff */
23 protected $memCache;
24
25 /** @var Array Map of paths to small (RAM/disk) cache items */
26 protected $cache = array(); // (storage path => key => value)
27 protected $maxCacheSize = 100; // integer; max paths with entries
28 /** @var Array Map of paths to large (RAM/disk) cache items */
29 protected $expensiveCache = array(); // (storage path => key => value)
30 protected $maxExpensiveCacheSize = 10; // integer; max paths with entries
31
32 /** @var Array Map of container names to sharding settings */
33 protected $shardViaHashLevels = array(); // (container name => config array)
34
35 protected $maxFileSize = 4294967296; // integer bytes (4GiB)
36
37 /**
38 * @see FileBackend::__construct()
39 *
40 * @param $config Array
41 */
42 public function __construct( array $config ) {
43 parent::__construct( $config );
44 $this->memCache = new EmptyBagOStuff(); // disabled by default
45 }
46
47 /**
48 * Get the maximum allowable file size given backend
49 * medium restrictions and basic performance constraints.
50 * Do not call this function from places outside FileBackend and FileOp.
51 *
52 * @return integer Bytes
53 */
54 final public function maxFileSizeInternal() {
55 return $this->maxFileSize;
56 }
57
58 /**
59 * Check if a file can be created at a given storage path.
60 * FS backends should check if the parent directory exists and the file is writable.
61 * Backends using key/value stores should check if the container exists.
62 *
63 * @param $storagePath string
64 * @return bool
65 */
66 abstract public function isPathUsableInternal( $storagePath );
67
68 /**
69 * Create a file in the backend with the given contents.
70 * Do not call this function from places outside FileBackend and FileOp.
71 *
72 * $params include:
73 * content : the raw file contents
74 * dst : destination storage path
75 * overwrite : overwrite any file that exists at the destination
76 *
77 * @param $params Array
78 * @return Status
79 */
80 final public function createInternal( array $params ) {
81 wfProfileIn( __METHOD__ );
82 wfProfileIn( __METHOD__ . '-' . $this->name );
83 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
84 $status = Status::newFatal( 'backend-fail-maxsize',
85 $params['dst'], $this->maxFileSizeInternal() );
86 } else {
87 $status = $this->doCreateInternal( $params );
88 $this->clearCache( array( $params['dst'] ) );
89 }
90 wfProfileOut( __METHOD__ . '-' . $this->name );
91 wfProfileOut( __METHOD__ );
92 return $status;
93 }
94
95 /**
96 * @see FileBackendStore::createInternal()
97 */
98 abstract protected function doCreateInternal( array $params );
99
100 /**
101 * Store a file into the backend from a file on disk.
102 * Do not call this function from places outside FileBackend and FileOp.
103 *
104 * $params include:
105 * src : source path on disk
106 * dst : destination storage path
107 * overwrite : overwrite any file that exists at the destination
108 *
109 * @param $params Array
110 * @return Status
111 */
112 final public function storeInternal( array $params ) {
113 wfProfileIn( __METHOD__ );
114 wfProfileIn( __METHOD__ . '-' . $this->name );
115 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
116 $status = Status::newFatal( 'backend-fail-store', $params['dst'] );
117 } else {
118 $status = $this->doStoreInternal( $params );
119 $this->clearCache( array( $params['dst'] ) );
120 }
121 wfProfileOut( __METHOD__ . '-' . $this->name );
122 wfProfileOut( __METHOD__ );
123 return $status;
124 }
125
126 /**
127 * @see FileBackendStore::storeInternal()
128 */
129 abstract protected function doStoreInternal( array $params );
130
131 /**
132 * Copy a file from one storage path to another in the backend.
133 * Do not call this function from places outside FileBackend and FileOp.
134 *
135 * $params include:
136 * src : source storage path
137 * dst : destination storage path
138 * overwrite : overwrite any file that exists at the destination
139 *
140 * @param $params Array
141 * @return Status
142 */
143 final public function copyInternal( array $params ) {
144 wfProfileIn( __METHOD__ );
145 wfProfileIn( __METHOD__ . '-' . $this->name );
146 $status = $this->doCopyInternal( $params );
147 $this->clearCache( array( $params['dst'] ) );
148 wfProfileOut( __METHOD__ . '-' . $this->name );
149 wfProfileOut( __METHOD__ );
150 return $status;
151 }
152
153 /**
154 * @see FileBackendStore::copyInternal()
155 */
156 abstract protected function doCopyInternal( array $params );
157
158 /**
159 * Delete a file at the storage path.
160 * Do not call this function from places outside FileBackend and FileOp.
161 *
162 * $params include:
163 * src : source storage path
164 * ignoreMissingSource : do nothing if the source file does not exist
165 *
166 * @param $params Array
167 * @return Status
168 */
169 final public function deleteInternal( array $params ) {
170 wfProfileIn( __METHOD__ );
171 wfProfileIn( __METHOD__ . '-' . $this->name );
172 $status = $this->doDeleteInternal( $params );
173 $this->clearCache( array( $params['src'] ) );
174 wfProfileOut( __METHOD__ . '-' . $this->name );
175 wfProfileOut( __METHOD__ );
176 return $status;
177 }
178
179 /**
180 * @see FileBackendStore::deleteInternal()
181 */
182 abstract protected function doDeleteInternal( array $params );
183
184 /**
185 * Move a file from one storage path to another in the backend.
186 * Do not call this function from places outside FileBackend and FileOp.
187 *
188 * $params include:
189 * src : source storage path
190 * dst : destination storage path
191 * overwrite : overwrite any file that exists at the destination
192 *
193 * @param $params Array
194 * @return Status
195 */
196 final public function moveInternal( array $params ) {
197 wfProfileIn( __METHOD__ );
198 wfProfileIn( __METHOD__ . '-' . $this->name );
199 $status = $this->doMoveInternal( $params );
200 $this->clearCache( array( $params['src'], $params['dst'] ) );
201 wfProfileOut( __METHOD__ . '-' . $this->name );
202 wfProfileOut( __METHOD__ );
203 return $status;
204 }
205
206 /**
207 * @see FileBackendStore::moveInternal()
208 * @return Status
209 */
210 protected function doMoveInternal( array $params ) {
211 // Copy source to dest
212 $status = $this->copyInternal( $params );
213 if ( $status->isOK() ) {
214 // Delete source (only fails due to races or medium going down)
215 $status->merge( $this->deleteInternal( array( 'src' => $params['src'] ) ) );
216 $status->setResult( true, $status->value ); // ignore delete() errors
217 }
218 return $status;
219 }
220
221 /**
222 * @see FileBackend::concatenate()
223 * @return Status
224 */
225 final public function concatenate( array $params ) {
226 wfProfileIn( __METHOD__ );
227 wfProfileIn( __METHOD__ . '-' . $this->name );
228 $status = Status::newGood();
229
230 // Try to lock the source files for the scope of this function
231 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager::LOCK_UW, $status );
232 if ( $status->isOK() ) {
233 // Actually do the concatenation
234 $status->merge( $this->doConcatenate( $params ) );
235 }
236
237 wfProfileOut( __METHOD__ . '-' . $this->name );
238 wfProfileOut( __METHOD__ );
239 return $status;
240 }
241
242 /**
243 * @see FileBackendStore::concatenate()
244 * @return Status
245 */
246 protected function doConcatenate( array $params ) {
247 $status = Status::newGood();
248 $tmpPath = $params['dst']; // convenience
249
250 // Check that the specified temp file is valid...
251 wfSuppressWarnings();
252 $ok = ( is_file( $tmpPath ) && !filesize( $tmpPath ) );
253 wfRestoreWarnings();
254 if ( !$ok ) { // not present or not empty
255 $status->fatal( 'backend-fail-opentemp', $tmpPath );
256 return $status;
257 }
258
259 // Build up the temp file using the source chunks (in order)...
260 $tmpHandle = fopen( $tmpPath, 'ab' );
261 if ( $tmpHandle === false ) {
262 $status->fatal( 'backend-fail-opentemp', $tmpPath );
263 return $status;
264 }
265 foreach ( $params['srcs'] as $virtualSource ) {
266 // Get a local FS version of the chunk
267 $tmpFile = $this->getLocalReference( array( 'src' => $virtualSource ) );
268 if ( !$tmpFile ) {
269 $status->fatal( 'backend-fail-read', $virtualSource );
270 return $status;
271 }
272 // Get a handle to the local FS version
273 $sourceHandle = fopen( $tmpFile->getPath(), 'r' );
274 if ( $sourceHandle === false ) {
275 fclose( $tmpHandle );
276 $status->fatal( 'backend-fail-read', $virtualSource );
277 return $status;
278 }
279 // Append chunk to file (pass chunk size to avoid magic quotes)
280 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
281 fclose( $sourceHandle );
282 fclose( $tmpHandle );
283 $status->fatal( 'backend-fail-writetemp', $tmpPath );
284 return $status;
285 }
286 fclose( $sourceHandle );
287 }
288 if ( !fclose( $tmpHandle ) ) {
289 $status->fatal( 'backend-fail-closetemp', $tmpPath );
290 return $status;
291 }
292
293 clearstatcache(); // temp file changed
294
295 return $status;
296 }
297
298 /**
299 * @see FileBackend::doPrepare()
300 * @return Status
301 */
302 final protected function doPrepare( array $params ) {
303 wfProfileIn( __METHOD__ );
304 wfProfileIn( __METHOD__ . '-' . $this->name );
305
306 $status = Status::newGood();
307 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
308 if ( $dir === null ) {
309 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
310 wfProfileOut( __METHOD__ . '-' . $this->name );
311 wfProfileOut( __METHOD__ );
312 return $status; // invalid storage path
313 }
314
315 if ( $shard !== null ) { // confined to a single container/shard
316 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
317 } else { // directory is on several shards
318 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
319 list( $b, $shortCont, $r ) = self::splitStoragePath( $params['dir'] );
320 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
321 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
322 }
323 }
324
325 wfProfileOut( __METHOD__ . '-' . $this->name );
326 wfProfileOut( __METHOD__ );
327 return $status;
328 }
329
330 /**
331 * @see FileBackendStore::doPrepare()
332 * @return Status
333 */
334 protected function doPrepareInternal( $container, $dir, array $params ) {
335 return Status::newGood();
336 }
337
338 /**
339 * @see FileBackend::doSecure()
340 * @return Status
341 */
342 final protected function doSecure( array $params ) {
343 wfProfileIn( __METHOD__ );
344 wfProfileIn( __METHOD__ . '-' . $this->name );
345 $status = Status::newGood();
346
347 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
348 if ( $dir === null ) {
349 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
350 wfProfileOut( __METHOD__ . '-' . $this->name );
351 wfProfileOut( __METHOD__ );
352 return $status; // invalid storage path
353 }
354
355 if ( $shard !== null ) { // confined to a single container/shard
356 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
357 } else { // directory is on several shards
358 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
359 list( $b, $shortCont, $r ) = self::splitStoragePath( $params['dir'] );
360 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
361 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
362 }
363 }
364
365 wfProfileOut( __METHOD__ . '-' . $this->name );
366 wfProfileOut( __METHOD__ );
367 return $status;
368 }
369
370 /**
371 * @see FileBackendStore::doSecure()
372 * @return Status
373 */
374 protected function doSecureInternal( $container, $dir, array $params ) {
375 return Status::newGood();
376 }
377
378 /**
379 * @see FileBackend::doClean()
380 * @return Status
381 */
382 final protected function doClean( array $params ) {
383 wfProfileIn( __METHOD__ );
384 wfProfileIn( __METHOD__ . '-' . $this->name );
385 $status = Status::newGood();
386
387 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
388 if ( $dir === null ) {
389 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
390 wfProfileOut( __METHOD__ . '-' . $this->name );
391 wfProfileOut( __METHOD__ );
392 return $status; // invalid storage path
393 }
394
395 // Attempt to lock this directory...
396 $filesLockEx = array( $params['dir'] );
397 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager::LOCK_EX, $status );
398 if ( !$status->isOK() ) {
399 wfProfileOut( __METHOD__ . '-' . $this->name );
400 wfProfileOut( __METHOD__ );
401 return $status; // abort
402 }
403
404 if ( $shard !== null ) { // confined to a single container/shard
405 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
406 $this->deleteContainerCache( $fullCont ); // purge cache
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->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
412 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
413 }
414 }
415
416 wfProfileOut( __METHOD__ . '-' . $this->name );
417 wfProfileOut( __METHOD__ );
418 return $status;
419 }
420
421 /**
422 * @see FileBackendStore::doClean()
423 * @return Status
424 */
425 protected function doCleanInternal( $container, $dir, array $params ) {
426 return Status::newGood();
427 }
428
429 /**
430 * @see FileBackend::fileExists()
431 * @return bool|null
432 */
433 final public function fileExists( array $params ) {
434 wfProfileIn( __METHOD__ );
435 wfProfileIn( __METHOD__ . '-' . $this->name );
436 $stat = $this->getFileStat( $params );
437 wfProfileOut( __METHOD__ . '-' . $this->name );
438 wfProfileOut( __METHOD__ );
439 return ( $stat === null ) ? null : (bool)$stat; // null => failure
440 }
441
442 /**
443 * @see FileBackend::getFileTimestamp()
444 * @return bool
445 */
446 final public function getFileTimestamp( array $params ) {
447 wfProfileIn( __METHOD__ );
448 wfProfileIn( __METHOD__ . '-' . $this->name );
449 $stat = $this->getFileStat( $params );
450 wfProfileOut( __METHOD__ . '-' . $this->name );
451 wfProfileOut( __METHOD__ );
452 return $stat ? $stat['mtime'] : false;
453 }
454
455 /**
456 * @see FileBackend::getFileSize()
457 * @return bool
458 */
459 final public function getFileSize( array $params ) {
460 wfProfileIn( __METHOD__ );
461 wfProfileIn( __METHOD__ . '-' . $this->name );
462 $stat = $this->getFileStat( $params );
463 wfProfileOut( __METHOD__ . '-' . $this->name );
464 wfProfileOut( __METHOD__ );
465 return $stat ? $stat['size'] : false;
466 }
467
468 /**
469 * @see FileBackend::getFileStat()
470 * @return bool
471 */
472 final public function getFileStat( array $params ) {
473 wfProfileIn( __METHOD__ );
474 wfProfileIn( __METHOD__ . '-' . $this->name );
475 $path = self::normalizeStoragePath( $params['src'] );
476 if ( $path === null ) {
477 wfProfileOut( __METHOD__ . '-' . $this->name );
478 wfProfileOut( __METHOD__ );
479 return false; // invalid storage path
480 }
481 $latest = !empty( $params['latest'] );
482 if ( isset( $this->cache[$path]['stat'] ) ) {
483 // If we want the latest data, check that this cached
484 // value was in fact fetched with the latest available data.
485 if ( !$latest || $this->cache[$path]['stat']['latest'] ) {
486 $this->pingCache( $path ); // LRU
487 wfProfileOut( __METHOD__ . '-' . $this->name );
488 wfProfileOut( __METHOD__ );
489 return $this->cache[$path]['stat'];
490 }
491 }
492 wfProfileIn( __METHOD__ . '-miss' );
493 wfProfileIn( __METHOD__ . '-miss-' . $this->name );
494 $stat = $this->doGetFileStat( $params );
495 wfProfileOut( __METHOD__ . '-miss-' . $this->name );
496 wfProfileOut( __METHOD__ . '-miss' );
497 if ( is_array( $stat ) ) { // don't cache negatives
498 $this->trimCache(); // limit memory
499 $this->cache[$path]['stat'] = $stat;
500 $this->cache[$path]['stat']['latest'] = $latest;
501 }
502 wfProfileOut( __METHOD__ . '-' . $this->name );
503 wfProfileOut( __METHOD__ );
504 return $stat;
505 }
506
507 /**
508 * @see FileBackendStore::getFileStat()
509 */
510 abstract protected function doGetFileStat( array $params );
511
512 /**
513 * @see FileBackend::getFileContents()
514 * @return bool|string
515 */
516 public function getFileContents( array $params ) {
517 wfProfileIn( __METHOD__ );
518 wfProfileIn( __METHOD__ . '-' . $this->name );
519 $tmpFile = $this->getLocalReference( $params );
520 if ( !$tmpFile ) {
521 wfProfileOut( __METHOD__ . '-' . $this->name );
522 wfProfileOut( __METHOD__ );
523 return false;
524 }
525 wfSuppressWarnings();
526 $data = file_get_contents( $tmpFile->getPath() );
527 wfRestoreWarnings();
528 wfProfileOut( __METHOD__ . '-' . $this->name );
529 wfProfileOut( __METHOD__ );
530 return $data;
531 }
532
533 /**
534 * @see FileBackend::getFileSha1Base36()
535 * @return bool|string
536 */
537 final public function getFileSha1Base36( array $params ) {
538 wfProfileIn( __METHOD__ );
539 wfProfileIn( __METHOD__ . '-' . $this->name );
540 $path = $params['src'];
541 if ( isset( $this->cache[$path]['sha1'] ) ) {
542 $this->pingCache( $path ); // LRU
543 wfProfileOut( __METHOD__ . '-' . $this->name );
544 wfProfileOut( __METHOD__ );
545 return $this->cache[$path]['sha1'];
546 }
547 wfProfileIn( __METHOD__ . '-miss' );
548 wfProfileIn( __METHOD__ . '-miss-' . $this->name );
549 $hash = $this->doGetFileSha1Base36( $params );
550 wfProfileOut( __METHOD__ . '-miss-' . $this->name );
551 wfProfileOut( __METHOD__ . '-miss' );
552 if ( $hash ) { // don't cache negatives
553 $this->trimCache(); // limit memory
554 $this->cache[$path]['sha1'] = $hash;
555 }
556 wfProfileOut( __METHOD__ . '-' . $this->name );
557 wfProfileOut( __METHOD__ );
558 return $hash;
559 }
560
561 /**
562 * @see FileBackendStore::getFileSha1Base36()
563 * @return bool
564 */
565 protected function doGetFileSha1Base36( array $params ) {
566 $fsFile = $this->getLocalReference( $params );
567 if ( !$fsFile ) {
568 return false;
569 } else {
570 return $fsFile->getSha1Base36();
571 }
572 }
573
574 /**
575 * @see FileBackend::getFileProps()
576 * @return Array
577 */
578 final public function getFileProps( array $params ) {
579 wfProfileIn( __METHOD__ );
580 wfProfileIn( __METHOD__ . '-' . $this->name );
581 $fsFile = $this->getLocalReference( $params );
582 $props = $fsFile ? $fsFile->getProps() : FSFile::placeholderProps();
583 wfProfileOut( __METHOD__ . '-' . $this->name );
584 wfProfileOut( __METHOD__ );
585 return $props;
586 }
587
588 /**
589 * @see FileBackend::getLocalReference()
590 * @return TempFSFile|null
591 */
592 public function getLocalReference( array $params ) {
593 wfProfileIn( __METHOD__ );
594 wfProfileIn( __METHOD__ . '-' . $this->name );
595 $path = $params['src'];
596 if ( isset( $this->expensiveCache[$path]['localRef'] ) ) {
597 $this->pingExpensiveCache( $path );
598 wfProfileOut( __METHOD__ . '-' . $this->name );
599 wfProfileOut( __METHOD__ );
600 return $this->expensiveCache[$path]['localRef'];
601 }
602 $tmpFile = $this->getLocalCopy( $params );
603 if ( $tmpFile ) { // don't cache negatives
604 $this->trimExpensiveCache(); // limit memory
605 $this->expensiveCache[$path]['localRef'] = $tmpFile;
606 }
607 wfProfileOut( __METHOD__ . '-' . $this->name );
608 wfProfileOut( __METHOD__ );
609 return $tmpFile;
610 }
611
612 /**
613 * @see FileBackend::streamFile()
614 * @return Status
615 */
616 final public function streamFile( array $params ) {
617 wfProfileIn( __METHOD__ );
618 wfProfileIn( __METHOD__ . '-' . $this->name );
619 $status = Status::newGood();
620
621 $info = $this->getFileStat( $params );
622 if ( !$info ) { // let StreamFile handle the 404
623 $status->fatal( 'backend-fail-notexists', $params['src'] );
624 }
625
626 // Set output buffer and HTTP headers for stream
627 $extraHeaders = isset( $params['headers'] ) ? $params['headers'] : array();
628 $res = StreamFile::prepareForStream( $params['src'], $info, $extraHeaders );
629 if ( $res == StreamFile::NOT_MODIFIED ) {
630 // do nothing; client cache is up to date
631 } elseif ( $res == StreamFile::READY_STREAM ) {
632 wfProfileIn( __METHOD__ . '-send' );
633 wfProfileIn( __METHOD__ . '-send-' . $this->name );
634 $status = $this->doStreamFile( $params );
635 wfProfileOut( __METHOD__ . '-send-' . $this->name );
636 wfProfileOut( __METHOD__ . '-send' );
637 } else {
638 $status->fatal( 'backend-fail-stream', $params['src'] );
639 }
640
641 wfProfileOut( __METHOD__ . '-' . $this->name );
642 wfProfileOut( __METHOD__ );
643 return $status;
644 }
645
646 /**
647 * @see FileBackendStore::streamFile()
648 * @return Status
649 */
650 protected function doStreamFile( array $params ) {
651 $status = Status::newGood();
652
653 $fsFile = $this->getLocalReference( $params );
654 if ( !$fsFile ) {
655 $status->fatal( 'backend-fail-stream', $params['src'] );
656 } elseif ( !readfile( $fsFile->getPath() ) ) {
657 $status->fatal( 'backend-fail-stream', $params['src'] );
658 }
659
660 return $status;
661 }
662
663 /**
664 * @copydoc FileBackend::getFileList()
665 * @return Array|null|Traversable
666 */
667 final public function getFileList( array $params ) {
668 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
669 if ( $dir === null ) { // invalid storage path
670 return null;
671 }
672 if ( $shard !== null ) {
673 // File listing is confined to a single container/shard
674 return $this->getFileListInternal( $fullCont, $dir, $params );
675 } else {
676 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
677 // File listing spans multiple containers/shards
678 list( $b, $shortCont, $r ) = self::splitStoragePath( $params['dir'] );
679 return new FileBackendStoreShardListIterator( $this,
680 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
681 }
682 }
683
684 /**
685 * Do not call this function from places outside FileBackend
686 *
687 * @see FileBackendStore::getFileList()
688 *
689 * @param $container string Resolved container name
690 * @param $dir string Resolved path relative to container
691 * @param $params Array
692 * @return Traversable|Array|null
693 */
694 abstract public function getFileListInternal( $container, $dir, array $params );
695
696 /**
697 * Get the list of supported operations and their corresponding FileOp classes.
698 *
699 * @return Array
700 */
701 protected function supportedOperations() {
702 return array(
703 'store' => 'StoreFileOp',
704 'copy' => 'CopyFileOp',
705 'move' => 'MoveFileOp',
706 'delete' => 'DeleteFileOp',
707 'create' => 'CreateFileOp',
708 'null' => 'NullFileOp'
709 );
710 }
711
712 /**
713 * Return a list of FileOp objects from a list of operations.
714 * Do not call this function from places outside FileBackend.
715 *
716 * The result must have the same number of items as the input.
717 * An exception is thrown if an unsupported operation is requested.
718 *
719 * @param $ops Array Same format as doOperations()
720 * @return Array List of FileOp objects
721 * @throws MWException
722 */
723 final public function getOperations( array $ops ) {
724 $supportedOps = $this->supportedOperations();
725
726 $performOps = array(); // array of FileOp objects
727 // Build up ordered array of FileOps...
728 foreach ( $ops as $operation ) {
729 $opName = $operation['op'];
730 if ( isset( $supportedOps[$opName] ) ) {
731 $class = $supportedOps[$opName];
732 // Get params for this operation
733 $params = $operation;
734 // Append the FileOp class
735 $performOps[] = new $class( $this, $params );
736 } else {
737 throw new MWException( "Operation `$opName` is not supported." );
738 }
739 }
740
741 return $performOps;
742 }
743
744 /**
745 * @see FileBackend::doOperationsInternal()
746 * @return Status
747 */
748 protected function doOperationsInternal( array $ops, array $opts ) {
749 wfProfileIn( __METHOD__ );
750 wfProfileIn( __METHOD__ . '-' . $this->name );
751 $status = Status::newGood();
752
753 // Build up a list of FileOps...
754 $performOps = $this->getOperations( $ops );
755
756 // Acquire any locks as needed...
757 if ( empty( $opts['nonLocking'] ) ) {
758 // Build up a list of files to lock...
759 $filesLockEx = $filesLockSh = array();
760 foreach ( $performOps as $fileOp ) {
761 $filesLockSh = array_merge( $filesLockSh, $fileOp->storagePathsRead() );
762 $filesLockEx = array_merge( $filesLockEx, $fileOp->storagePathsChanged() );
763 }
764 // Optimization: if doing an EX lock anyway, don't also set an SH one
765 $filesLockSh = array_diff( $filesLockSh, $filesLockEx );
766 // Get a shared lock on the parent directory of each path changed
767 $filesLockSh = array_merge( $filesLockSh, array_map( 'dirname', $filesLockEx ) );
768 // Try to lock those files for the scope of this function...
769 $scopeLockS = $this->getScopedFileLocks( $filesLockSh, LockManager::LOCK_UW, $status );
770 $scopeLockE = $this->getScopedFileLocks( $filesLockEx, LockManager::LOCK_EX, $status );
771 if ( !$status->isOK() ) {
772 wfProfileOut( __METHOD__ . '-' . $this->name );
773 wfProfileOut( __METHOD__ );
774 return $status; // abort
775 }
776 }
777
778 // Clear any file cache entries (after locks acquired)
779 $this->clearCache();
780
781 // Load from the persistent container cache
782 $this->primeContainerCache( $performOps );
783
784 // Actually attempt the operation batch...
785 $subStatus = FileOp::attemptBatch( $performOps, $opts, $this->fileJournal );
786
787 // Merge errors into status fields
788 $status->merge( $subStatus );
789 $status->success = $subStatus->success; // not done in merge()
790
791 wfProfileOut( __METHOD__ . '-' . $this->name );
792 wfProfileOut( __METHOD__ );
793 return $status;
794 }
795
796 /**
797 * @see FileBackend::clearCache()
798 */
799 final public function clearCache( array $paths = null ) {
800 if ( is_array( $paths ) ) {
801 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
802 $paths = array_filter( $paths, 'strlen' ); // remove nulls
803 }
804 if ( $paths === null ) {
805 $this->cache = array();
806 $this->expensiveCache = array();
807 } else {
808 foreach ( $paths as $path ) {
809 unset( $this->cache[$path] );
810 unset( $this->expensiveCache[$path] );
811 }
812 }
813 $this->doClearCache( $paths );
814 }
815
816 /**
817 * Clears any additional stat caches for storage paths
818 *
819 * @see FileBackend::clearCache()
820 *
821 * @param $paths Array Storage paths (optional)
822 * @return void
823 */
824 protected function doClearCache( array $paths = null ) {}
825
826 /**
827 * Move a cache entry to the top (such as when accessed)
828 *
829 * @param $path string Storage path
830 */
831 protected function pingCache( $path ) {
832 if ( isset( $this->cache[$path] ) ) {
833 $tmp = $this->cache[$path];
834 unset( $this->cache[$path] );
835 $this->cache[$path] = $tmp;
836 }
837 }
838
839 /**
840 * Prune the inexpensive cache if it is too big to add an item
841 *
842 * @return void
843 */
844 protected function trimCache() {
845 if ( count( $this->cache ) >= $this->maxCacheSize ) {
846 reset( $this->cache );
847 unset( $this->cache[key( $this->cache )] );
848 }
849 }
850
851 /**
852 * Move a cache entry to the top (such as when accessed)
853 *
854 * @param $path string Storage path
855 */
856 protected function pingExpensiveCache( $path ) {
857 if ( isset( $this->expensiveCache[$path] ) ) {
858 $tmp = $this->expensiveCache[$path];
859 unset( $this->expensiveCache[$path] );
860 $this->expensiveCache[$path] = $tmp;
861 }
862 }
863
864 /**
865 * Prune the expensive cache if it is too big to add an item
866 *
867 * @return void
868 */
869 protected function trimExpensiveCache() {
870 if ( count( $this->expensiveCache ) >= $this->maxExpensiveCacheSize ) {
871 reset( $this->expensiveCache );
872 unset( $this->expensiveCache[key( $this->expensiveCache )] );
873 }
874 }
875
876 /**
877 * Check if a container name is valid.
878 * This checks for for length and illegal characters.
879 *
880 * @param $container string
881 * @return bool
882 */
883 final protected static function isValidContainerName( $container ) {
884 // This accounts for Swift and S3 restrictions while leaving room
885 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
886 // This disallows directory separators or traversal characters.
887 // Note that matching strings URL encode to the same string;
888 // in Swift, the length restriction is *after* URL encoding.
889 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
890 }
891
892 /**
893 * Splits a storage path into an internal container name,
894 * an internal relative file name, and a container shard suffix.
895 * Any shard suffix is already appended to the internal container name.
896 * This also checks that the storage path is valid and within this backend.
897 *
898 * If the container is sharded but a suffix could not be determined,
899 * this means that the path can only refer to a directory and can only
900 * be scanned by looking in all the container shards.
901 *
902 * @param $storagePath string
903 * @return Array (container, path, container suffix) or (null, null, null) if invalid
904 */
905 final protected function resolveStoragePath( $storagePath ) {
906 list( $backend, $container, $relPath ) = self::splitStoragePath( $storagePath );
907 if ( $backend === $this->name ) { // must be for this backend
908 $relPath = self::normalizeContainerPath( $relPath );
909 if ( $relPath !== null ) {
910 // Get shard for the normalized path if this container is sharded
911 $cShard = $this->getContainerShard( $container, $relPath );
912 // Validate and sanitize the relative path (backend-specific)
913 $relPath = $this->resolveContainerPath( $container, $relPath );
914 if ( $relPath !== null ) {
915 // Prepend any wiki ID prefix to the container name
916 $container = $this->fullContainerName( $container );
917 if ( self::isValidContainerName( $container ) ) {
918 // Validate and sanitize the container name (backend-specific)
919 $container = $this->resolveContainerName( "{$container}{$cShard}" );
920 if ( $container !== null ) {
921 return array( $container, $relPath, $cShard );
922 }
923 }
924 }
925 }
926 }
927 return array( null, null, null );
928 }
929
930 /**
931 * Like resolveStoragePath() except null values are returned if
932 * the container is sharded and the shard could not be determined.
933 *
934 * @see FileBackendStore::resolveStoragePath()
935 *
936 * @param $storagePath string
937 * @return Array (container, path) or (null, null) if invalid
938 */
939 final protected function resolveStoragePathReal( $storagePath ) {
940 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
941 if ( $cShard !== null ) {
942 return array( $container, $relPath );
943 }
944 return array( null, null );
945 }
946
947 /**
948 * Get the container name shard suffix for a given path.
949 * Any empty suffix means the container is not sharded.
950 *
951 * @param $container string Container name
952 * @param $relStoragePath string Storage path relative to the container
953 * @return string|null Returns null if shard could not be determined
954 */
955 final protected function getContainerShard( $container, $relPath ) {
956 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
957 if ( $levels == 1 || $levels == 2 ) {
958 // Hash characters are either base 16 or 36
959 $char = ( $base == 36 ) ? '[0-9a-z]' : '[0-9a-f]';
960 // Get a regex that represents the shard portion of paths.
961 // The concatenation of the captures gives us the shard.
962 if ( $levels === 1 ) { // 16 or 36 shards per container
963 $hashDirRegex = '(' . $char . ')';
964 } else { // 256 or 1296 shards per container
965 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
966 $hashDirRegex = $char . '/(' . $char . '{2})';
967 } else { // short hash dir format (e.g. "a/b/c")
968 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
969 }
970 }
971 // Allow certain directories to be above the hash dirs so as
972 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
973 // They must be 2+ chars to avoid any hash directory ambiguity.
974 $m = array();
975 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
976 return '.' . implode( '', array_slice( $m, 1 ) );
977 }
978 return null; // failed to match
979 }
980 return ''; // no sharding
981 }
982
983 /**
984 * Get the sharding config for a container.
985 * If greater than 0, then all file storage paths within
986 * the container are required to be hashed accordingly.
987 *
988 * @param $container string
989 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
990 */
991 final protected function getContainerHashLevels( $container ) {
992 if ( isset( $this->shardViaHashLevels[$container] ) ) {
993 $config = $this->shardViaHashLevels[$container];
994 $hashLevels = (int)$config['levels'];
995 if ( $hashLevels == 1 || $hashLevels == 2 ) {
996 $hashBase = (int)$config['base'];
997 if ( $hashBase == 16 || $hashBase == 36 ) {
998 return array( $hashLevels, $hashBase, $config['repeat'] );
999 }
1000 }
1001 }
1002 return array( 0, 0, false ); // no sharding
1003 }
1004
1005 /**
1006 * Get a list of full container shard suffixes for a container
1007 *
1008 * @param $container string
1009 * @return Array
1010 */
1011 final protected function getContainerSuffixes( $container ) {
1012 $shards = array();
1013 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1014 if ( $digits > 0 ) {
1015 $numShards = pow( $base, $digits );
1016 for ( $index = 0; $index < $numShards; $index++ ) {
1017 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1018 }
1019 }
1020 return $shards;
1021 }
1022
1023 /**
1024 * Get the full container name, including the wiki ID prefix
1025 *
1026 * @param $container string
1027 * @return string
1028 */
1029 final protected function fullContainerName( $container ) {
1030 if ( $this->wikiId != '' ) {
1031 return "{$this->wikiId}-$container";
1032 } else {
1033 return $container;
1034 }
1035 }
1036
1037 /**
1038 * Resolve a container name, checking if it's allowed by the backend.
1039 * This is intended for internal use, such as encoding illegal chars.
1040 * Subclasses can override this to be more restrictive.
1041 *
1042 * @param $container string
1043 * @return string|null
1044 */
1045 protected function resolveContainerName( $container ) {
1046 return $container;
1047 }
1048
1049 /**
1050 * Resolve a relative storage path, checking if it's allowed by the backend.
1051 * This is intended for internal use, such as encoding illegal chars or perhaps
1052 * getting absolute paths (e.g. FS based backends). Note that the relative path
1053 * may be the empty string (e.g. the path is simply to the container).
1054 *
1055 * @param $container string Container name
1056 * @param $relStoragePath string Storage path relative to the container
1057 * @return string|null Path or null if not valid
1058 */
1059 protected function resolveContainerPath( $container, $relStoragePath ) {
1060 return $relStoragePath;
1061 }
1062
1063 /**
1064 * Get the cache key for a container
1065 *
1066 * @param $container Resolved container name
1067 * @return string
1068 */
1069 private function containerCacheKey( $container ) {
1070 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1071 }
1072
1073 /**
1074 * Set the cached info for a container
1075 *
1076 * @param $container Resolved container name
1077 * @param $val mixed Information to cache
1078 * @return void
1079 */
1080 final protected function setContainerCache( $container, $val ) {
1081 $this->memCache->set( $this->containerCacheKey( $container ), $val, 7*86400 );
1082 }
1083
1084 /**
1085 * Delete the cached info for a container
1086 *
1087 * @param $container Resolved container name
1088 * @return void
1089 */
1090 final protected function deleteContainerCache( $container ) {
1091 $this->memCache->delete( $this->containerCacheKey( $container ) );
1092 }
1093
1094 /**
1095 * Do a batch lookup from cache for container stats for all containers
1096 * used in a list of container names, storage paths, or FileOp objects.
1097 *
1098 * @param $items Array List of storage paths or FileOps
1099 * @return void
1100 */
1101 final protected function primeContainerCache( array $items ) {
1102 $paths = array(); // list of storage paths
1103 $contNames = array(); // (cache key => resolved container name)
1104 // Get all the paths/containers from the items...
1105 foreach ( $items as $item ) {
1106 if ( $item instanceof FileOp ) {
1107 $paths = array_merge( $paths, $item->storagePathsRead() );
1108 $paths = array_merge( $paths, $item->storagePathsChanged() );
1109 } elseif ( self::isStoragePath( $item ) ) {
1110 $paths[] = $item;
1111 } elseif ( is_string( $item ) ) { // full container name
1112 $contNames[$this->containerCacheKey( $item )] = $item;
1113 }
1114 }
1115 // Get all the corresponding cache keys for paths...
1116 foreach ( $paths as $path ) {
1117 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1118 if ( $fullCont !== null ) { // valid path for this backend
1119 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1120 }
1121 }
1122
1123 $contInfo = array(); // (resolved container name => cache value)
1124 // Get all cache entries for these container cache keys...
1125 $values = $this->memCache->getBatch( array_keys( $contNames ) );
1126 foreach ( $values as $cacheKey => $val ) {
1127 $contInfo[$contNames[$cacheKey]] = $val;
1128 }
1129
1130 // Populate the container process cache for the backend...
1131 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1132 }
1133
1134 /**
1135 * Fill the backend-specific process cache given an array of
1136 * resolved container names and their corresponding cached info.
1137 * Only containers that actually exist should appear in the map.
1138 *
1139 * @param $containerInfo Array Map of resolved container names to cached info
1140 * @return void
1141 */
1142 protected function doPrimeContainerCache( array $containerInfo ) {}
1143 }
1144
1145 /**
1146 * FileBackendStore helper function to handle file listings that span container shards.
1147 * Do not use this class from places outside of FileBackendStore.
1148 *
1149 * @ingroup FileBackend
1150 */
1151 class FileBackendStoreShardListIterator implements Iterator {
1152 /* @var FileBackendStore */
1153 protected $backend;
1154 /* @var Array */
1155 protected $params;
1156 /* @var Array */
1157 protected $shardSuffixes;
1158 protected $container; // string
1159 protected $directory; // string
1160
1161 /* @var Traversable */
1162 protected $iter;
1163 protected $curShard = 0; // integer
1164 protected $pos = 0; // integer
1165
1166 /**
1167 * @param $backend FileBackendStore
1168 * @param $container string Full storage container name
1169 * @param $dir string Storage directory relative to container
1170 * @param $suffixes Array List of container shard suffixes
1171 * @param $params Array
1172 */
1173 public function __construct(
1174 FileBackendStore $backend, $container, $dir, array $suffixes, array $params
1175 ) {
1176 $this->backend = $backend;
1177 $this->container = $container;
1178 $this->directory = $dir;
1179 $this->shardSuffixes = $suffixes;
1180 $this->params = $params;
1181 }
1182
1183 /**
1184 * @see Iterator::current()
1185 * @return string|bool String or false
1186 */
1187 public function current() {
1188 if ( is_array( $this->iter ) ) {
1189 return current( $this->iter );
1190 } else {
1191 return $this->iter->current();
1192 }
1193 }
1194
1195 /**
1196 * @see Iterator::key()
1197 * @return integer
1198 */
1199 public function key() {
1200 return $this->pos;
1201 }
1202
1203 /**
1204 * @see Iterator::next()
1205 * @return void
1206 */
1207 public function next() {
1208 ++$this->pos;
1209 if ( is_array( $this->iter ) ) {
1210 next( $this->iter );
1211 } else {
1212 $this->iter->next();
1213 }
1214 // Find the next non-empty shard if no elements are left
1215 $this->nextShardIteratorIfNotValid();
1216 }
1217
1218 /**
1219 * @see Iterator::rewind()
1220 * @return void
1221 */
1222 public function rewind() {
1223 $this->pos = 0;
1224 $this->curShard = 0;
1225 $this->setIteratorFromCurrentShard();
1226 // Find the next non-empty shard if this one has no elements
1227 $this->nextShardIteratorIfNotValid();
1228 }
1229
1230 /**
1231 * @see Iterator::valid()
1232 * @return bool
1233 */
1234 public function valid() {
1235 if ( $this->iter == null ) {
1236 return false; // some failure?
1237 } elseif ( is_array( $this->iter ) ) {
1238 return ( current( $this->iter ) !== false ); // no paths can have this value
1239 } else {
1240 return $this->iter->valid();
1241 }
1242 }
1243
1244 /**
1245 * If the list iterator for this container shard is out of items,
1246 * then move on to the next container that has items.
1247 * If there are none, then it advances to the last container.
1248 */
1249 protected function nextShardIteratorIfNotValid() {
1250 while ( !$this->valid() ) {
1251 if ( ++$this->curShard >= count( $this->shardSuffixes ) ) {
1252 break; // no more container shards
1253 }
1254 $this->setIteratorFromCurrentShard();
1255 }
1256 }
1257
1258 /**
1259 * Set the list iterator to that of the current container shard
1260 */
1261 protected function setIteratorFromCurrentShard() {
1262 $suffix = $this->shardSuffixes[$this->curShard];
1263 $this->iter = $this->backend->getFileListInternal(
1264 "{$this->container}{$suffix}", $this->directory, $this->params );
1265 }
1266 }