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