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