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