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