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