Merge "Special:Upload should not crash on failing previews"
[mediawiki.git] / includes / libs / filebackend / fileop / FileOp.php
blobfab5a3743c1e6cfa7cebc89e269ac2d23172f1ff
1 <?php
2 /**
3 * Helper class for representing operations with transaction support.
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.
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.
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
20 * @file
21 * @ingroup FileBackend
22 * @author Aaron Schulz
24 use Psr\Log\LoggerInterface;
26 /**
27 * FileBackend helper class for representing operations.
28 * Do not use this class from places outside FileBackend.
30 * Methods called from FileOpBatch::attempt() should avoid throwing
31 * exceptions at all costs. FileOp objects should be lightweight in order
32 * to support large arrays in memory and serialization.
34 * @ingroup FileBackend
35 * @since 1.19
37 abstract class FileOp {
38 /** @var array */
39 protected $params = [];
41 /** @var FileBackendStore */
42 protected $backend;
43 /** @var LoggerInterface */
44 protected $logger;
46 /** @var int */
47 protected $state = self::STATE_NEW;
49 /** @var bool */
50 protected $failed = false;
52 /** @var bool */
53 protected $async = false;
55 /** @var string */
56 protected $batchId;
58 /** @var bool Operation is not a no-op */
59 protected $doOperation = true;
61 /** @var string */
62 protected $sourceSha1;
64 /** @var bool */
65 protected $overwriteSameCase;
67 /** @var bool */
68 protected $destExists;
70 /* Object life-cycle */
71 const STATE_NEW = 1;
72 const STATE_CHECKED = 2;
73 const STATE_ATTEMPTED = 3;
75 /**
76 * Build a new batch file operation transaction
78 * @param FileBackendStore $backend
79 * @param array $params
80 * @param LoggerInterface $logger PSR logger instance
81 * @throws FileBackendError
83 final public function __construct(
84 FileBackendStore $backend, array $params, LoggerInterface $logger
85 ) {
86 $this->backend = $backend;
87 $this->logger = $logger;
88 list( $required, $optional, $paths ) = $this->allowedParams();
89 foreach ( $required as $name ) {
90 if ( isset( $params[$name] ) ) {
91 $this->params[$name] = $params[$name];
92 } else {
93 throw new InvalidArgumentException( "File operation missing parameter '$name'." );
96 foreach ( $optional as $name ) {
97 if ( isset( $params[$name] ) ) {
98 $this->params[$name] = $params[$name];
101 foreach ( $paths as $name ) {
102 if ( isset( $this->params[$name] ) ) {
103 // Normalize paths so the paths to the same file have the same string
104 $this->params[$name] = self::normalizeIfValidStoragePath( $this->params[$name] );
110 * Normalize a string if it is a valid storage path
112 * @param string $path
113 * @return string
115 protected static function normalizeIfValidStoragePath( $path ) {
116 if ( FileBackend::isStoragePath( $path ) ) {
117 $res = FileBackend::normalizeStoragePath( $path );
119 return ( $res !== null ) ? $res : $path;
122 return $path;
126 * Set the batch UUID this operation belongs to
128 * @param string $batchId
130 final public function setBatchId( $batchId ) {
131 $this->batchId = $batchId;
135 * Get the value of the parameter with the given name
137 * @param string $name
138 * @return mixed Returns null if the parameter is not set
140 final public function getParam( $name ) {
141 return isset( $this->params[$name] ) ? $this->params[$name] : null;
145 * Check if this operation failed precheck() or attempt()
147 * @return bool
149 final public function failed() {
150 return $this->failed;
154 * Get a new empty predicates array for precheck()
156 * @return array
158 final public static function newPredicates() {
159 return [ 'exists' => [], 'sha1' => [] ];
163 * Get a new empty dependency tracking array for paths read/written to
165 * @return array
167 final public static function newDependencies() {
168 return [ 'read' => [], 'write' => [] ];
172 * Update a dependency tracking array to account for this operation
174 * @param array $deps Prior path reads/writes; format of FileOp::newPredicates()
175 * @return array
177 final public function applyDependencies( array $deps ) {
178 $deps['read'] += array_fill_keys( $this->storagePathsRead(), 1 );
179 $deps['write'] += array_fill_keys( $this->storagePathsChanged(), 1 );
181 return $deps;
185 * Check if this operation changes files listed in $paths
187 * @param array $deps Prior path reads/writes; format of FileOp::newPredicates()
188 * @return bool
190 final public function dependsOn( array $deps ) {
191 foreach ( $this->storagePathsChanged() as $path ) {
192 if ( isset( $deps['read'][$path] ) || isset( $deps['write'][$path] ) ) {
193 return true; // "output" or "anti" dependency
196 foreach ( $this->storagePathsRead() as $path ) {
197 if ( isset( $deps['write'][$path] ) ) {
198 return true; // "flow" dependency
202 return false;
206 * Get the file journal entries for this file operation
208 * @param array $oPredicates Pre-op info about files (format of FileOp::newPredicates)
209 * @param array $nPredicates Post-op info about files (format of FileOp::newPredicates)
210 * @return array
212 final public function getJournalEntries( array $oPredicates, array $nPredicates ) {
213 if ( !$this->doOperation ) {
214 return []; // this is a no-op
216 $nullEntries = [];
217 $updateEntries = [];
218 $deleteEntries = [];
219 $pathsUsed = array_merge( $this->storagePathsRead(), $this->storagePathsChanged() );
220 foreach ( array_unique( $pathsUsed ) as $path ) {
221 $nullEntries[] = [ // assertion for recovery
222 'op' => 'null',
223 'path' => $path,
224 'newSha1' => $this->fileSha1( $path, $oPredicates )
227 foreach ( $this->storagePathsChanged() as $path ) {
228 if ( $nPredicates['sha1'][$path] === false ) { // deleted
229 $deleteEntries[] = [
230 'op' => 'delete',
231 'path' => $path,
232 'newSha1' => ''
234 } else { // created/updated
235 $updateEntries[] = [
236 'op' => $this->fileExists( $path, $oPredicates ) ? 'update' : 'create',
237 'path' => $path,
238 'newSha1' => $nPredicates['sha1'][$path]
243 return array_merge( $nullEntries, $updateEntries, $deleteEntries );
247 * Check preconditions of the operation without writing anything.
248 * This must update $predicates for each path that the op can change
249 * except when a failing StatusValue object is returned.
251 * @param array $predicates
252 * @return StatusValue
254 final public function precheck( array &$predicates ) {
255 if ( $this->state !== self::STATE_NEW ) {
256 return StatusValue::newFatal( 'fileop-fail-state', self::STATE_NEW, $this->state );
258 $this->state = self::STATE_CHECKED;
259 $status = $this->doPrecheck( $predicates );
260 if ( !$status->isOK() ) {
261 $this->failed = true;
264 return $status;
268 * @param array $predicates
269 * @return StatusValue
271 protected function doPrecheck( array &$predicates ) {
272 return StatusValue::newGood();
276 * Attempt the operation
278 * @return StatusValue
280 final public function attempt() {
281 if ( $this->state !== self::STATE_CHECKED ) {
282 return StatusValue::newFatal( 'fileop-fail-state', self::STATE_CHECKED, $this->state );
283 } elseif ( $this->failed ) { // failed precheck
284 return StatusValue::newFatal( 'fileop-fail-attempt-precheck' );
286 $this->state = self::STATE_ATTEMPTED;
287 if ( $this->doOperation ) {
288 $status = $this->doAttempt();
289 if ( !$status->isOK() ) {
290 $this->failed = true;
291 $this->logFailure( 'attempt' );
293 } else { // no-op
294 $status = StatusValue::newGood();
297 return $status;
301 * @return StatusValue
303 protected function doAttempt() {
304 return StatusValue::newGood();
308 * Attempt the operation in the background
310 * @return StatusValue
312 final public function attemptAsync() {
313 $this->async = true;
314 $result = $this->attempt();
315 $this->async = false;
317 return $result;
321 * Get the file operation parameters
323 * @return array (required params list, optional params list, list of params that are paths)
325 protected function allowedParams() {
326 return [ [], [], [] ];
330 * Adjust params to FileBackendStore internal file calls
332 * @param array $params
333 * @return array (required params list, optional params list)
335 protected function setFlags( array $params ) {
336 return [ 'async' => $this->async ] + $params;
340 * Get a list of storage paths read from for this operation
342 * @return array
344 public function storagePathsRead() {
345 return [];
349 * Get a list of storage paths written to for this operation
351 * @return array
353 public function storagePathsChanged() {
354 return [];
358 * Check for errors with regards to the destination file already existing.
359 * Also set the destExists, overwriteSameCase and sourceSha1 member variables.
360 * A bad StatusValue will be returned if there is no chance it can be overwritten.
362 * @param array $predicates
363 * @return StatusValue
365 protected function precheckDestExistence( array $predicates ) {
366 $status = StatusValue::newGood();
367 // Get hash of source file/string and the destination file
368 $this->sourceSha1 = $this->getSourceSha1Base36(); // FS file or data string
369 if ( $this->sourceSha1 === null ) { // file in storage?
370 $this->sourceSha1 = $this->fileSha1( $this->params['src'], $predicates );
372 $this->overwriteSameCase = false;
373 $this->destExists = $this->fileExists( $this->params['dst'], $predicates );
374 if ( $this->destExists ) {
375 if ( $this->getParam( 'overwrite' ) ) {
376 return $status; // OK
377 } elseif ( $this->getParam( 'overwriteSame' ) ) {
378 $dhash = $this->fileSha1( $this->params['dst'], $predicates );
379 // Check if hashes are valid and match each other...
380 if ( !strlen( $this->sourceSha1 ) || !strlen( $dhash ) ) {
381 $status->fatal( 'backend-fail-hashes' );
382 } elseif ( $this->sourceSha1 !== $dhash ) {
383 // Give an error if the files are not identical
384 $status->fatal( 'backend-fail-notsame', $this->params['dst'] );
385 } else {
386 $this->overwriteSameCase = true; // OK
389 return $status; // do nothing; either OK or bad status
390 } else {
391 $status->fatal( 'backend-fail-alreadyexists', $this->params['dst'] );
393 return $status;
397 return $status;
401 * precheckDestExistence() helper function to get the source file SHA-1.
402 * Subclasses should overwride this if the source is not in storage.
404 * @return string|bool Returns false on failure
406 protected function getSourceSha1Base36() {
407 return null; // N/A
411 * Check if a file will exist in storage when this operation is attempted
413 * @param string $source Storage path
414 * @param array $predicates
415 * @return bool
417 final protected function fileExists( $source, array $predicates ) {
418 if ( isset( $predicates['exists'][$source] ) ) {
419 return $predicates['exists'][$source]; // previous op assures this
420 } else {
421 $params = [ 'src' => $source, 'latest' => true ];
423 return $this->backend->fileExists( $params );
428 * Get the SHA-1 of a file in storage when this operation is attempted
430 * @param string $source Storage path
431 * @param array $predicates
432 * @return string|bool False on failure
434 final protected function fileSha1( $source, array $predicates ) {
435 if ( isset( $predicates['sha1'][$source] ) ) {
436 return $predicates['sha1'][$source]; // previous op assures this
437 } elseif ( isset( $predicates['exists'][$source] ) && !$predicates['exists'][$source] ) {
438 return false; // previous op assures this
439 } else {
440 $params = [ 'src' => $source, 'latest' => true ];
442 return $this->backend->getFileSha1Base36( $params );
447 * Get the backend this operation is for
449 * @return FileBackendStore
451 public function getBackend() {
452 return $this->backend;
456 * Log a file operation failure and preserve any temp files
458 * @param string $action
460 final public function logFailure( $action ) {
461 $params = $this->params;
462 $params['failedAction'] = $action;
463 try {
464 $this->logger->error( get_class( $this ) .
465 " failed (batch #{$this->batchId}): " . FormatJson::encode( $params ) );
466 } catch ( Exception $e ) {
467 // bad config? debug log error?