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