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