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