aboutsummaryrefslogtreecommitdiffstats
path: root/includes/libs/filebackend/fileop/FileOp.php
blob: 9d9e5b05b9869325c88521d3cbc475c38edef3d0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
<?php
/**
 * Helper class for representing operations with transaction support.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 * @ingroup FileBackend
 */

namespace Wikimedia\FileBackend\FileOps;

use Closure;
use Exception;
use InvalidArgumentException;
use Psr\Log\LoggerInterface;
use StatusValue;
use Wikimedia\FileBackend\FileBackend;
use Wikimedia\FileBackend\FileBackendStore;
use Wikimedia\RequestTimeout\TimeoutException;

/**
 * FileBackend helper class for representing operations.
 * Do not use this class from places outside FileBackend.
 *
 * Methods called from FileOpBatch::attempt() should avoid throwing
 * exceptions at all costs. FileOp objects should be lightweight in order
 * to support large arrays in memory and serialization.
 *
 * @ingroup FileBackend
 * @since 1.19
 */
abstract class FileOp {
	/** @var FileBackendStore */
	protected $backend;
	/** @var LoggerInterface */
	protected $logger;

	/** @var array */
	protected $params = [];

	/** @var int Stage in the operation life-cycle */
	protected $state = self::STATE_NEW;
	/** @var bool Whether the operation pre-check or attempt stage failed */
	protected $failed = false;
	/** @var bool Whether the operation is part of a concurrent sub-batch of operation */
	protected $async = false;
	/** @var bool Whether the operation pre-check stage marked the attempt stage as a no-op */
	protected $noOp = false;

	/** @var bool|null */
	protected $overwriteSameCase;
	/** @var bool|null */
	protected $destExists;

	/** Operation has not yet been pre-checked nor run */
	private const STATE_NEW = 1;
	/** Operation has been pre-checked but not yet attempted */
	private const STATE_CHECKED = 2;
	/** Operation has been attempted */
	private const STATE_ATTEMPTED = 3;

	/**
	 * Build a new batch file operation transaction
	 *
	 * @param FileBackendStore $backend
	 * @param array $params
	 * @param LoggerInterface $logger PSR logger instance
	 */
	final public function __construct(
		FileBackendStore $backend, array $params, LoggerInterface $logger
	) {
		$this->backend = $backend;
		$this->logger = $logger;
		[ $required, $optional, $paths ] = $this->allowedParams();
		foreach ( $required as $name ) {
			if ( isset( $params[$name] ) ) {
				$this->params[$name] = $params[$name];
			} else {
				throw new InvalidArgumentException( "File operation missing parameter '$name'." );
			}
		}
		foreach ( $optional as $name ) {
			if ( isset( $params[$name] ) ) {
				$this->params[$name] = $params[$name];
			}
		}
		foreach ( $paths as $name ) {
			if ( isset( $this->params[$name] ) ) {
				// Normalize paths so the paths to the same file have the same string
				$this->params[$name] = self::normalizeIfValidStoragePath( $this->params[$name] );
			}
		}
	}

	/**
	 * Normalize a string if it is a valid storage path
	 *
	 * @param string $path
	 * @return string
	 */
	protected static function normalizeIfValidStoragePath( $path ) {
		if ( FileBackend::isStoragePath( $path ) ) {
			$res = FileBackend::normalizeStoragePath( $path );

			return $res ?? $path;
		}

		return $path;
	}

	/**
	 * Get the value of the parameter with the given name
	 *
	 * @param string $name
	 * @return mixed Returns null if the parameter is not set
	 */
	final public function getParam( $name ) {
		return $this->params[$name] ?? null;
	}

	/**
	 * Check if this operation failed precheck() or attempt()
	 *
	 * @return bool
	 */
	final public function failed() {
		return $this->failed;
	}

	/**
	 * Get a new empty dependency tracking array for paths read/written to
	 *
	 * @return array
	 */
	final public static function newDependencies() {
		return [ 'read' => [], 'write' => [] ];
	}

	/**
	 * Update a dependency tracking array to account for this operation
	 *
	 * @param array $deps Prior path reads/writes; format of FileOp::newDependencies()
	 * @return array
	 */
	final public function applyDependencies( array $deps ) {
		$deps['read'] += array_fill_keys( $this->storagePathsRead(), 1 );
		$deps['write'] += array_fill_keys( $this->storagePathsChanged(), 1 );

		return $deps;
	}

	/**
	 * Check if this operation changes files listed in $paths
	 *
	 * @param array $deps Prior path reads/writes; format of FileOp::newDependencies()
	 * @return bool
	 */
	final public function dependsOn( array $deps ) {
		foreach ( $this->storagePathsChanged() as $path ) {
			if ( isset( $deps['read'][$path] ) || isset( $deps['write'][$path] ) ) {
				return true; // "output" or "anti" dependency
			}
		}
		foreach ( $this->storagePathsRead() as $path ) {
			if ( isset( $deps['write'][$path] ) ) {
				return true; // "flow" dependency
			}
		}

		return false;
	}

	/**
	 * Do a dry-run precondition check of the operation in the context of op batch
	 *
	 * Updates the batch predicates for all paths this op can change if an OK status is returned
	 *
	 * @param FileStatePredicates $predicates Counterfactual file states for the op batch
	 * @return StatusValue
	 */
	final public function precheck( FileStatePredicates $predicates ) {
		if ( $this->state !== self::STATE_NEW ) {
			return StatusValue::newFatal( 'fileop-fail-state', self::STATE_NEW, $this->state );
		}
		$this->state = self::STATE_CHECKED;

		$status = StatusValue::newGood();
		foreach ( $this->storagePathsReadOrChanged() as $path ) {
			if ( !$this->backend->isPathUsableInternal( $path ) ) {
				$status->fatal( 'backend-fail-usable', $path );
			}
		}
		if ( !$status->isOK() ) {
			return $status;
		}

		$opPredicates = $predicates->snapshot( $this->storagePathsReadOrChanged() );
		$status = $this->doPrecheck( $opPredicates, $predicates );
		if ( !$status->isOK() ) {
			$this->failed = true;
		}

		return $status;
	}

	/**
	 * Do a dry-run precondition check of the operation in the context of op batch
	 *
	 * Updates the batch predicates for all paths this op can change if an OK status is returned
	 *
	 * @param FileStatePredicates $opPredicates Counterfactual file states for op paths at op start
	 * @param FileStatePredicates $batchPredicates Counterfactual file states for the op batch
	 * @return StatusValue
	 */
	protected function doPrecheck(
		FileStatePredicates $opPredicates,
		FileStatePredicates $batchPredicates
	) {
		return StatusValue::newGood();
	}

	/**
	 * Attempt the operation
	 *
	 * @return StatusValue
	 */
	final public function attempt() {
		if ( $this->state !== self::STATE_CHECKED ) {
			return StatusValue::newFatal( 'fileop-fail-state', self::STATE_CHECKED, $this->state );
		} elseif ( $this->failed ) { // failed precheck
			return StatusValue::newFatal( 'fileop-fail-attempt-precheck' );
		}
		$this->state = self::STATE_ATTEMPTED;
		if ( $this->noOp ) {
			$status = StatusValue::newGood(); // no-op
		} else {
			$status = $this->doAttempt();
			if ( !$status->isOK() ) {
				$this->failed = true;
				$this->logFailure( 'attempt' );
			}
		}

		return $status;
	}

	/**
	 * @return StatusValue
	 */
	protected function doAttempt() {
		return StatusValue::newGood();
	}

	/**
	 * Attempt the operation in the background
	 *
	 * @return StatusValue
	 */
	final public function attemptAsync() {
		$this->async = true;
		$result = $this->attempt();
		$this->async = false;

		return $result;
	}

	/**
	 * Attempt the operation without regards to prechecks
	 *
	 * @return StatusValue
	 */
	final public function attemptQuick() {
		$this->state = self::STATE_CHECKED; // bypassed

		return $this->attempt();
	}

	/**
	 * Attempt the operation in the background without regards to prechecks
	 *
	 * @return StatusValue
	 */
	final public function attemptAsyncQuick() {
		$this->state = self::STATE_CHECKED; // bypassed

		return $this->attemptAsync();
	}

	/**
	 * Get the file operation parameters
	 *
	 * @return array (required params list, optional params list, list of params that are paths)
	 */
	protected function allowedParams() {
		return [ [], [], [] ];
	}

	/**
	 * Adjust params to FileBackendStore internal file calls
	 *
	 * @param array $params
	 * @return array (required params list, optional params list)
	 */
	protected function setFlags( array $params ) {
		return [ 'async' => $this->async ] + $params;
	}

	/**
	 * Get a list of storage paths read from for this operation
	 *
	 * @return array
	 */
	public function storagePathsRead() {
		return [];
	}

	/**
	 * Get a list of storage paths written to for this operation
	 *
	 * @return array
	 */
	public function storagePathsChanged() {
		return [];
	}

	/**
	 * Get a list of storage paths read from or written to for this operation
	 *
	 * @return array
	 */
	final public function storagePathsReadOrChanged() {
		return array_values( array_unique(
			array_merge( $this->storagePathsRead(), $this->storagePathsChanged() )
		) );
	}

	/**
	 * Check for errors with regards to the destination file already existing
	 *
	 * Also set the destExists and overwriteSameCase member variables.
	 * A bad StatusValue will be returned if there is no chance it can be overwritten.
	 *
	 * @param FileStatePredicates $opPredicates Counterfactual storage path states for this op
	 * @param int|false|Closure $sourceSize Source size or idempotent function yielding the size
	 * @param string|Closure $sourceSha1 Source hash, or, idempotent function yielding the hash
	 * @return StatusValue
	 */
	protected function precheckDestExistence(
		FileStatePredicates $opPredicates,
		$sourceSize,
		$sourceSha1
	) {
		$status = StatusValue::newGood();
		// Record the existence of destination file
		$this->destExists = $this->resolveFileExistence( $this->params['dst'], $opPredicates );
		// Check if an incompatible file exists at the destination
		$this->overwriteSameCase = false;
		if ( $this->destExists ) {
			if ( $this->getParam( 'overwrite' ) ) {
				return $status; // OK, no conflict
			} elseif ( $this->getParam( 'overwriteSame' ) ) {
				// Operation does nothing other than return an OK or bad status
				$sourceSize = ( $sourceSize instanceof Closure ) ? $sourceSize() : $sourceSize;
				$sourceSha1 = ( $sourceSha1 instanceof Closure ) ? $sourceSha1() : $sourceSha1;
				$dstSha1 = $this->resolveFileSha1Base36( $this->params['dst'], $opPredicates );
				$dstSize = $this->resolveFileSize( $this->params['dst'], $opPredicates );
				// Check if hashes are valid and match each other...
				if ( !strlen( $sourceSha1 ) || !strlen( $dstSha1 ) ) {
					$status->fatal( 'backend-fail-hashes' );
				} elseif ( !is_int( $sourceSize ) || !is_int( $dstSize ) ) {
					$status->fatal( 'backend-fail-sizes' );
				} elseif ( $sourceSha1 !== $dstSha1 || $sourceSize !== $dstSize ) {
					// Give an error if the files are not identical
					$status->fatal( 'backend-fail-notsame', $this->params['dst'] );
				} else {
					$this->overwriteSameCase = true; // OK
				}
			} else {
				$status->fatal( 'backend-fail-alreadyexists', $this->params['dst'] );
			}
		} elseif ( $this->destExists === FileBackend::EXISTENCE_ERROR ) {
			$status->fatal( 'backend-fail-stat', $this->params['dst'] );
		}

		return $status;
	}

	/**
	 * Check if a file will exist in storage when this operation is attempted
	 *
	 * Ideally, the file stat entry should already be preloaded via preloadFileStat().
	 * Otherwise, this will query the backend.
	 *
	 * @param string $source Storage path
	 * @param FileStatePredicates $opPredicates Counterfactual storage path states for this op
	 * @return bool|null Whether the file will exist or null on error
	 */
	final protected function resolveFileExistence( $source, FileStatePredicates $opPredicates ) {
		return $opPredicates->resolveFileExistence(
			$source,
			function ( $path ) {
				return $this->backend->fileExists( [ 'src' => $path, 'latest' => true ] );
			}
		);
	}

	/**
	 * Get the size a file in storage will have when this operation is attempted
	 *
	 * Ideally, file the stat entry should already be preloaded via preloadFileStat() and
	 * the backend tracks hashes as extended attributes. Otherwise, this will query the backend.
	 * Get the size of a file in storage when this operation is attempted
	 *
	 * @param string $source Storage path
	 * @param FileStatePredicates $opPredicates Counterfactual storage path states for this op
	 * @return int|false False on failure
	 */
	final protected function resolveFileSize( $source, FileStatePredicates $opPredicates ) {
		return $opPredicates->resolveFileSize(
			$source,
			function ( $path ) {
				return $this->backend->getFileSize( [ 'src' => $path, 'latest' => true ] );
			}
		);
	}

	/**
	 * Get the SHA-1 of a file in storage when this operation is attempted
	 *
	 * @param string $source Storage path
	 * @param FileStatePredicates $opPredicates Counterfactual storage path states for this op
	 * @return string|false The SHA-1 hash the file will have or false if non-existent or on error
	 */
	final protected function resolveFileSha1Base36( $source, FileStatePredicates $opPredicates ) {
		return $opPredicates->resolveFileSha1Base36(
			$source,
			function ( $path ) {
				return $this->backend->getFileSha1Base36( [ 'src' => $path, 'latest' => true ] );
			}
		);
	}

	/**
	 * Get the backend this operation is for
	 *
	 * @return FileBackendStore
	 */
	public function getBackend() {
		return $this->backend;
	}

	/**
	 * Log a file operation failure and preserve any temp files
	 *
	 * @param string $action
	 */
	final public function logFailure( $action ) {
		try {
			$this->logger->error( static::class . ' failed: ' . $action,
				[ 'params' => $this->params ]
			);
		} catch ( TimeoutException $e ) {
			throw $e;
		} catch ( Exception $e ) {
			// bad config? debug log error?
		}
	}
}

/** @deprecated class alias since 1.43 */
class_alias( FileOp::class, 'FileOp' );