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