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