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