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