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