Merge "Don't display multiple language links to the same language"
[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 * @return Array List of corresponding Status objects
1180 */
1181 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1182 foreach ( $fileOpHandles as $fileOpHandle ) { // OK if empty
1183 throw new MWException( "This backend supports no asynchronous operations." );
1184 }
1185 return array();
1186 }
1187
1188 /**
1189 * @see FileBackend::preloadCache()
1190 */
1191 final public function preloadCache( array $paths ) {
1192 $fullConts = array(); // full container names
1193 foreach ( $paths as $path ) {
1194 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1195 $fullConts[] = $fullCont;
1196 }
1197 // Load from the persistent file and container caches
1198 $this->primeContainerCache( $fullConts );
1199 $this->primeFileCache( $paths );
1200 }
1201
1202 /**
1203 * @see FileBackend::clearCache()
1204 */
1205 final public function clearCache( array $paths = null ) {
1206 if ( is_array( $paths ) ) {
1207 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1208 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1209 }
1210 if ( $paths === null ) {
1211 $this->cheapCache->clear();
1212 $this->expensiveCache->clear();
1213 } else {
1214 foreach ( $paths as $path ) {
1215 $this->cheapCache->clear( $path );
1216 $this->expensiveCache->clear( $path );
1217 }
1218 }
1219 $this->doClearCache( $paths );
1220 }
1221
1222 /**
1223 * Clears any additional stat caches for storage paths
1224 *
1225 * @see FileBackend::clearCache()
1226 *
1227 * @param $paths Array Storage paths (optional)
1228 * @return void
1229 */
1230 protected function doClearCache( array $paths = null ) {}
1231
1232 /**
1233 * Is this a key/value store where directories are just virtual?
1234 * Virtual directories exists in so much as files exists that are
1235 * prefixed with the directory path followed by a forward slash.
1236 *
1237 * @return bool
1238 */
1239 abstract protected function directoriesAreVirtual();
1240
1241 /**
1242 * Check if a container name is valid.
1243 * This checks for for length and illegal characters.
1244 *
1245 * @param $container string
1246 * @return bool
1247 */
1248 final protected static function isValidContainerName( $container ) {
1249 // This accounts for Swift and S3 restrictions while leaving room
1250 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1251 // This disallows directory separators or traversal characters.
1252 // Note that matching strings URL encode to the same string;
1253 // in Swift, the length restriction is *after* URL encoding.
1254 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1255 }
1256
1257 /**
1258 * Splits a storage path into an internal container name,
1259 * an internal relative file name, and a container shard suffix.
1260 * Any shard suffix is already appended to the internal container name.
1261 * This also checks that the storage path is valid and within this backend.
1262 *
1263 * If the container is sharded but a suffix could not be determined,
1264 * this means that the path can only refer to a directory and can only
1265 * be scanned by looking in all the container shards.
1266 *
1267 * @param $storagePath string
1268 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1269 */
1270 final protected function resolveStoragePath( $storagePath ) {
1271 list( $backend, $container, $relPath ) = self::splitStoragePath( $storagePath );
1272 if ( $backend === $this->name ) { // must be for this backend
1273 $relPath = self::normalizeContainerPath( $relPath );
1274 if ( $relPath !== null ) {
1275 // Get shard for the normalized path if this container is sharded
1276 $cShard = $this->getContainerShard( $container, $relPath );
1277 // Validate and sanitize the relative path (backend-specific)
1278 $relPath = $this->resolveContainerPath( $container, $relPath );
1279 if ( $relPath !== null ) {
1280 // Prepend any wiki ID prefix to the container name
1281 $container = $this->fullContainerName( $container );
1282 if ( self::isValidContainerName( $container ) ) {
1283 // Validate and sanitize the container name (backend-specific)
1284 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1285 if ( $container !== null ) {
1286 return array( $container, $relPath, $cShard );
1287 }
1288 }
1289 }
1290 }
1291 }
1292 return array( null, null, null );
1293 }
1294
1295 /**
1296 * Like resolveStoragePath() except null values are returned if
1297 * the container is sharded and the shard could not be determined.
1298 *
1299 * @see FileBackendStore::resolveStoragePath()
1300 *
1301 * @param $storagePath string
1302 * @return Array (container, path) or (null, null) if invalid
1303 */
1304 final protected function resolveStoragePathReal( $storagePath ) {
1305 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1306 if ( $cShard !== null ) {
1307 return array( $container, $relPath );
1308 }
1309 return array( null, null );
1310 }
1311
1312 /**
1313 * Get the container name shard suffix for a given path.
1314 * Any empty suffix means the container is not sharded.
1315 *
1316 * @param $container string Container name
1317 * @param $relPath string Storage path relative to the container
1318 * @return string|null Returns null if shard could not be determined
1319 */
1320 final protected function getContainerShard( $container, $relPath ) {
1321 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1322 if ( $levels == 1 || $levels == 2 ) {
1323 // Hash characters are either base 16 or 36
1324 $char = ( $base == 36 ) ? '[0-9a-z]' : '[0-9a-f]';
1325 // Get a regex that represents the shard portion of paths.
1326 // The concatenation of the captures gives us the shard.
1327 if ( $levels === 1 ) { // 16 or 36 shards per container
1328 $hashDirRegex = '(' . $char . ')';
1329 } else { // 256 or 1296 shards per container
1330 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1331 $hashDirRegex = $char . '/(' . $char . '{2})';
1332 } else { // short hash dir format (e.g. "a/b/c")
1333 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1334 }
1335 }
1336 // Allow certain directories to be above the hash dirs so as
1337 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1338 // They must be 2+ chars to avoid any hash directory ambiguity.
1339 $m = array();
1340 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1341 return '.' . implode( '', array_slice( $m, 1 ) );
1342 }
1343 return null; // failed to match
1344 }
1345 return ''; // no sharding
1346 }
1347
1348 /**
1349 * Check if a storage path maps to a single shard.
1350 * Container dirs like "a", where the container shards on "x/xy",
1351 * can reside on several shards. Such paths are tricky to handle.
1352 *
1353 * @param $storagePath string Storage path
1354 * @return bool
1355 */
1356 final public function isSingleShardPathInternal( $storagePath ) {
1357 list( $c, $r, $shard ) = $this->resolveStoragePath( $storagePath );
1358 return ( $shard !== null );
1359 }
1360
1361 /**
1362 * Get the sharding config for a container.
1363 * If greater than 0, then all file storage paths within
1364 * the container are required to be hashed accordingly.
1365 *
1366 * @param $container string
1367 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
1368 */
1369 final protected function getContainerHashLevels( $container ) {
1370 if ( isset( $this->shardViaHashLevels[$container] ) ) {
1371 $config = $this->shardViaHashLevels[$container];
1372 $hashLevels = (int)$config['levels'];
1373 if ( $hashLevels == 1 || $hashLevels == 2 ) {
1374 $hashBase = (int)$config['base'];
1375 if ( $hashBase == 16 || $hashBase == 36 ) {
1376 return array( $hashLevels, $hashBase, $config['repeat'] );
1377 }
1378 }
1379 }
1380 return array( 0, 0, false ); // no sharding
1381 }
1382
1383 /**
1384 * Get a list of full container shard suffixes for a container
1385 *
1386 * @param $container string
1387 * @return Array
1388 */
1389 final protected function getContainerSuffixes( $container ) {
1390 $shards = array();
1391 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1392 if ( $digits > 0 ) {
1393 $numShards = pow( $base, $digits );
1394 for ( $index = 0; $index < $numShards; $index++ ) {
1395 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1396 }
1397 }
1398 return $shards;
1399 }
1400
1401 /**
1402 * Get the full container name, including the wiki ID prefix
1403 *
1404 * @param $container string
1405 * @return string
1406 */
1407 final protected function fullContainerName( $container ) {
1408 if ( $this->wikiId != '' ) {
1409 return "{$this->wikiId}-$container";
1410 } else {
1411 return $container;
1412 }
1413 }
1414
1415 /**
1416 * Resolve a container name, checking if it's allowed by the backend.
1417 * This is intended for internal use, such as encoding illegal chars.
1418 * Subclasses can override this to be more restrictive.
1419 *
1420 * @param $container string
1421 * @return string|null
1422 */
1423 protected function resolveContainerName( $container ) {
1424 return $container;
1425 }
1426
1427 /**
1428 * Resolve a relative storage path, checking if it's allowed by the backend.
1429 * This is intended for internal use, such as encoding illegal chars or perhaps
1430 * getting absolute paths (e.g. FS based backends). Note that the relative path
1431 * may be the empty string (e.g. the path is simply to the container).
1432 *
1433 * @param $container string Container name
1434 * @param $relStoragePath string Storage path relative to the container
1435 * @return string|null Path or null if not valid
1436 */
1437 protected function resolveContainerPath( $container, $relStoragePath ) {
1438 return $relStoragePath;
1439 }
1440
1441 /**
1442 * Get the cache key for a container
1443 *
1444 * @param $container string Resolved container name
1445 * @return string
1446 */
1447 private function containerCacheKey( $container ) {
1448 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1449 }
1450
1451 /**
1452 * Set the cached info for a container
1453 *
1454 * @param $container string Resolved container name
1455 * @param $val mixed Information to cache
1456 */
1457 final protected function setContainerCache( $container, $val ) {
1458 $this->memCache->add( $this->containerCacheKey( $container ), $val, 14*86400 );
1459 }
1460
1461 /**
1462 * Delete the cached info for a container.
1463 * The cache key is salted for a while to prevent race conditions.
1464 *
1465 * @param $container string Resolved container name
1466 */
1467 final protected function deleteContainerCache( $container ) {
1468 if ( !$this->memCache->set( $this->containerCacheKey( $container ), 'PURGED', 300 ) ) {
1469 trigger_error( "Unable to delete stat cache for container $container." );
1470 }
1471 }
1472
1473 /**
1474 * Do a batch lookup from cache for container stats for all containers
1475 * used in a list of container names, storage paths, or FileOp objects.
1476 *
1477 * @param $items Array
1478 * @return void
1479 */
1480 final protected function primeContainerCache( array $items ) {
1481 wfProfileIn( __METHOD__ );
1482 wfProfileIn( __METHOD__ . '-' . $this->name );
1483
1484 $paths = array(); // list of storage paths
1485 $contNames = array(); // (cache key => resolved container name)
1486 // Get all the paths/containers from the items...
1487 foreach ( $items as $item ) {
1488 if ( $item instanceof FileOp ) {
1489 $paths = array_merge( $paths, $item->storagePathsRead() );
1490 $paths = array_merge( $paths, $item->storagePathsChanged() );
1491 } elseif ( self::isStoragePath( $item ) ) {
1492 $paths[] = $item;
1493 } elseif ( is_string( $item ) ) { // full container name
1494 $contNames[$this->containerCacheKey( $item )] = $item;
1495 }
1496 }
1497 // Get all the corresponding cache keys for paths...
1498 foreach ( $paths as $path ) {
1499 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1500 if ( $fullCont !== null ) { // valid path for this backend
1501 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1502 }
1503 }
1504
1505 $contInfo = array(); // (resolved container name => cache value)
1506 // Get all cache entries for these container cache keys...
1507 $values = $this->memCache->getMulti( array_keys( $contNames ) );
1508 foreach ( $values as $cacheKey => $val ) {
1509 $contInfo[$contNames[$cacheKey]] = $val;
1510 }
1511
1512 // Populate the container process cache for the backend...
1513 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1514
1515 wfProfileOut( __METHOD__ . '-' . $this->name );
1516 wfProfileOut( __METHOD__ );
1517 }
1518
1519 /**
1520 * Fill the backend-specific process cache given an array of
1521 * resolved container names and their corresponding cached info.
1522 * Only containers that actually exist should appear in the map.
1523 *
1524 * @param $containerInfo Array Map of resolved container names to cached info
1525 * @return void
1526 */
1527 protected function doPrimeContainerCache( array $containerInfo ) {}
1528
1529 /**
1530 * Get the cache key for a file path
1531 *
1532 * @param $path string Storage path
1533 * @return string
1534 */
1535 private function fileCacheKey( $path ) {
1536 return wfMemcKey( 'backend', $this->getName(), 'file', sha1( $path ) );
1537 }
1538
1539 /**
1540 * Set the cached stat info for a file path.
1541 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1542 * salting for the case when a file is created at a path were there was none before.
1543 *
1544 * @param $path string Storage path
1545 * @param $val mixed Information to cache
1546 */
1547 final protected function setFileCache( $path, $val ) {
1548 $this->memCache->add( $this->fileCacheKey( $path ), $val, 7*86400 );
1549 }
1550
1551 /**
1552 * Delete the cached stat info for a file path.
1553 * The cache key is salted for a while to prevent race conditions.
1554 *
1555 * @param $path string Storage path
1556 */
1557 final protected function deleteFileCache( $path ) {
1558 if ( !$this->memCache->set( $this->fileCacheKey( $path ), 'PURGED', 300 ) ) {
1559 trigger_error( "Unable to delete stat cache for file $path." );
1560 }
1561 }
1562
1563 /**
1564 * Do a batch lookup from cache for file stats for all paths
1565 * used in a list of storage paths or FileOp objects.
1566 *
1567 * @param $items Array List of storage paths or FileOps
1568 * @return void
1569 */
1570 final protected function primeFileCache( array $items ) {
1571 wfProfileIn( __METHOD__ );
1572 wfProfileIn( __METHOD__ . '-' . $this->name );
1573
1574 $paths = array(); // list of storage paths
1575 $pathNames = array(); // (cache key => storage path)
1576 // Get all the paths/containers from the items...
1577 foreach ( $items as $item ) {
1578 if ( $item instanceof FileOp ) {
1579 $paths = array_merge( $paths, $item->storagePathsRead() );
1580 $paths = array_merge( $paths, $item->storagePathsChanged() );
1581 } elseif ( self::isStoragePath( $item ) ) {
1582 $paths[] = $item;
1583 }
1584 }
1585 // Get all the corresponding cache keys for paths...
1586 foreach ( $paths as $path ) {
1587 list( $cont, $rel, $s ) = $this->resolveStoragePath( $path );
1588 if ( $rel !== null ) { // valid path for this backend
1589 $pathNames[$this->fileCacheKey( $path )] = $path;
1590 }
1591 }
1592 // Get all cache entries for these container cache keys...
1593 $values = $this->memCache->getMulti( array_keys( $pathNames ) );
1594 foreach ( $values as $cacheKey => $val ) {
1595 if ( is_array( $val ) ) {
1596 $path = $pathNames[$cacheKey];
1597 $this->cheapCache->set( $path, 'stat', $val );
1598 if ( isset( $val['sha1'] ) ) { // some backends store SHA-1 as metadata
1599 $this->cheapCache->set( $path, 'sha1',
1600 array( 'hash' => $val['sha1'], 'latest' => $val['latest'] ) );
1601 }
1602 }
1603 }
1604
1605 wfProfileOut( __METHOD__ . '-' . $this->name );
1606 wfProfileOut( __METHOD__ );
1607 }
1608
1609 /**
1610 * Set the 'concurrency' option from a list of operation options
1611 *
1612 * @param $opts array Map of operation options
1613 * @return Array
1614 */
1615 final protected function setConcurrencyFlags( array $opts ) {
1616 $opts['concurrency'] = 1; // off
1617 if ( $this->parallelize === 'implicit' ) {
1618 if ( !isset( $opts['parallelize'] ) || $opts['parallelize'] ) {
1619 $opts['concurrency'] = $this->concurrency;
1620 }
1621 } elseif ( $this->parallelize === 'explicit' ) {
1622 if ( !empty( $opts['parallelize'] ) ) {
1623 $opts['concurrency'] = $this->concurrency;
1624 }
1625 }
1626 return $opts;
1627 }
1628 }
1629
1630 /**
1631 * FileBackendStore helper class for performing asynchronous file operations.
1632 *
1633 * For example, calling FileBackendStore::createInternal() with the "async"
1634 * param flag may result in a Status that contains this object as a value.
1635 * This class is largely backend-specific and is mostly just "magic" to be
1636 * passed to FileBackendStore::executeOpHandlesInternal().
1637 */
1638 abstract class FileBackendStoreOpHandle {
1639 /** @var Array */
1640 public $params = array(); // params to caller functions
1641 /** @var FileBackendStore */
1642 public $backend;
1643 /** @var Array */
1644 public $resourcesToClose = array();
1645
1646 public $call; // string; name that identifies the function called
1647
1648 /**
1649 * Close all open file handles
1650 *
1651 * @return void
1652 */
1653 public function closeResources() {
1654 array_map( 'fclose', $this->resourcesToClose );
1655 }
1656 }
1657
1658 /**
1659 * FileBackendStore helper function to handle listings that span container shards.
1660 * Do not use this class from places outside of FileBackendStore.
1661 *
1662 * @ingroup FileBackend
1663 */
1664 abstract class FileBackendStoreShardListIterator implements Iterator {
1665 /** @var FileBackendStore */
1666 protected $backend;
1667 /** @var Array */
1668 protected $params;
1669 /** @var Array */
1670 protected $shardSuffixes;
1671 protected $container; // string; full container name
1672 protected $directory; // string; resolved relative path
1673
1674 /** @var Traversable */
1675 protected $iter;
1676 protected $curShard = 0; // integer
1677 protected $pos = 0; // integer
1678
1679 /** @var Array */
1680 protected $multiShardPaths = array(); // (rel path => 1)
1681
1682 /**
1683 * @param $backend FileBackendStore
1684 * @param $container string Full storage container name
1685 * @param $dir string Storage directory relative to container
1686 * @param $suffixes Array List of container shard suffixes
1687 * @param $params Array
1688 */
1689 public function __construct(
1690 FileBackendStore $backend, $container, $dir, array $suffixes, array $params
1691 ) {
1692 $this->backend = $backend;
1693 $this->container = $container;
1694 $this->directory = $dir;
1695 $this->shardSuffixes = $suffixes;
1696 $this->params = $params;
1697 }
1698
1699 /**
1700 * @see Iterator::key()
1701 * @return integer
1702 */
1703 public function key() {
1704 return $this->pos;
1705 }
1706
1707 /**
1708 * @see Iterator::valid()
1709 * @return bool
1710 */
1711 public function valid() {
1712 if ( $this->iter instanceof Iterator ) {
1713 return $this->iter->valid();
1714 } elseif ( is_array( $this->iter ) ) {
1715 return ( current( $this->iter ) !== false ); // no paths can have this value
1716 }
1717 return false; // some failure?
1718 }
1719
1720 /**
1721 * @see Iterator::current()
1722 * @return string|bool String or false
1723 */
1724 public function current() {
1725 return ( $this->iter instanceof Iterator )
1726 ? $this->iter->current()
1727 : current( $this->iter );
1728 }
1729
1730 /**
1731 * @see Iterator::next()
1732 * @return void
1733 */
1734 public function next() {
1735 ++$this->pos;
1736 ( $this->iter instanceof Iterator ) ? $this->iter->next() : next( $this->iter );
1737 do {
1738 $continue = false; // keep scanning shards?
1739 $this->filterViaNext(); // filter out duplicates
1740 // Find the next non-empty shard if no elements are left
1741 if ( !$this->valid() ) {
1742 $this->nextShardIteratorIfNotValid();
1743 $continue = $this->valid(); // re-filter unless we ran out of shards
1744 }
1745 } while ( $continue );
1746 }
1747
1748 /**
1749 * @see Iterator::rewind()
1750 * @return void
1751 */
1752 public function rewind() {
1753 $this->pos = 0;
1754 $this->curShard = 0;
1755 $this->setIteratorFromCurrentShard();
1756 do {
1757 $continue = false; // keep scanning shards?
1758 $this->filterViaNext(); // filter out duplicates
1759 // Find the next non-empty shard if no elements are left
1760 if ( !$this->valid() ) {
1761 $this->nextShardIteratorIfNotValid();
1762 $continue = $this->valid(); // re-filter unless we ran out of shards
1763 }
1764 } while ( $continue );
1765 }
1766
1767 /**
1768 * Filter out duplicate items by advancing to the next ones
1769 */
1770 protected function filterViaNext() {
1771 while ( $this->valid() ) {
1772 $rel = $this->iter->current(); // path relative to given directory
1773 $path = $this->params['dir'] . "/{$rel}"; // full storage path
1774 if ( $this->backend->isSingleShardPathInternal( $path ) ) {
1775 break; // path is only on one shard; no issue with duplicates
1776 } elseif ( isset( $this->multiShardPaths[$rel] ) ) {
1777 // Don't keep listing paths that are on multiple shards
1778 ( $this->iter instanceof Iterator ) ? $this->iter->next() : next( $this->iter );
1779 } else {
1780 $this->multiShardPaths[$rel] = 1;
1781 break;
1782 }
1783 }
1784 }
1785
1786 /**
1787 * If the list iterator for this container shard is out of items,
1788 * then move on to the next container that has items.
1789 * If there are none, then it advances to the last container.
1790 */
1791 protected function nextShardIteratorIfNotValid() {
1792 while ( !$this->valid() && ++$this->curShard < count( $this->shardSuffixes ) ) {
1793 $this->setIteratorFromCurrentShard();
1794 }
1795 }
1796
1797 /**
1798 * Set the list iterator to that of the current container shard
1799 */
1800 protected function setIteratorFromCurrentShard() {
1801 $this->iter = $this->listFromShard(
1802 $this->container . $this->shardSuffixes[$this->curShard],
1803 $this->directory, $this->params );
1804 // Start loading results so that current() works
1805 if ( $this->iter ) {
1806 ( $this->iter instanceof Iterator ) ? $this->iter->rewind() : reset( $this->iter );
1807 }
1808 }
1809
1810 /**
1811 * Get the list for a given container shard
1812 *
1813 * @param $container string Resolved container name
1814 * @param $dir string Resolved path relative to container
1815 * @param $params Array
1816 * @return Traversable|Array|null
1817 */
1818 abstract protected function listFromShard( $container, $dir, array $params );
1819 }
1820
1821 /**
1822 * Iterator for listing directories
1823 */
1824 class FileBackendStoreShardDirIterator extends FileBackendStoreShardListIterator {
1825 /**
1826 * @see FileBackendStoreShardListIterator::listFromShard()
1827 * @return Array|null|Traversable
1828 */
1829 protected function listFromShard( $container, $dir, array $params ) {
1830 return $this->backend->getDirectoryListInternal( $container, $dir, $params );
1831 }
1832 }
1833
1834 /**
1835 * Iterator for listing regular files
1836 */
1837 class FileBackendStoreShardFileIterator extends FileBackendStoreShardListIterator {
1838 /**
1839 * @see FileBackendStoreShardListIterator::listFromShard()
1840 * @return Array|null|Traversable
1841 */
1842 protected function listFromShard( $container, $dir, array $params ) {
1843 return $this->backend->getFileListInternal( $container, $dir, $params );
1844 }
1845 }