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