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