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