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