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