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