MediaWiki master
copyFileBackend.php
Go to the documentation of this file.
1<?php
25
26// @codeCoverageIgnoreStart
27require_once __DIR__ . '/Maintenance.php';
28// @codeCoverageIgnoreEnd
29
43 protected $statCache = null;
44
45 public function __construct() {
46 parent::__construct();
47 $this->addDescription( 'Copy files in one backend to another.' );
48 $this->addOption( 'src', 'Backend containing the source files', true, true );
49 $this->addOption( 'dst', 'Backend where files should be copied to', true, true );
50 $this->addOption( 'containers', 'Pipe separated list of containers', true, true );
51 $this->addOption( 'subdir', 'Only do items in this child directory', false, true );
52 $this->addOption( 'ratefile', 'File to check periodically for batch size', false, true );
53 $this->addOption( 'prestat', 'Stat the destination files first (try to use listings)' );
54 $this->addOption( 'skiphash', 'Skip SHA-1 sync checks for files' );
55 $this->addOption( 'missingonly', 'Only copy files missing from destination listing' );
56 $this->addOption( 'syncviadelete', 'Delete destination files missing from source listing' );
57 $this->addOption( 'utf8only', 'Skip source files that do not have valid UTF-8 names' );
58 $this->setBatchSize( 50 );
59 }
60
61 public function execute() {
62 $backendGroup = $this->getServiceContainer()->getFileBackendGroup();
63 $src = $backendGroup->get( $this->getOption( 'src' ) );
64 $dst = $backendGroup->get( $this->getOption( 'dst' ) );
65 $containers = explode( '|', $this->getOption( 'containers' ) );
66 $subDir = rtrim( $this->getOption( 'subdir', '' ), '/' );
67
68 $rateFile = $this->getOption( 'ratefile' );
69
70 foreach ( $containers as $container ) {
71 if ( $subDir != '' ) {
72 $backendRel = "$container/$subDir";
73 $this->output( "Doing container '$container', directory '$subDir'...\n" );
74 } else {
75 $backendRel = $container;
76 $this->output( "Doing container '$container'...\n" );
77 }
78
79 if ( $this->hasOption( 'missingonly' ) ) {
80 $this->output( "\tBuilding list of missing files..." );
81 $srcPathsRel = $this->getListingDiffRel( $src, $dst, $backendRel );
82 $this->output( count( $srcPathsRel ) . " file(s) need to be copied.\n" );
83 } else {
84 $srcPathsRel = $src->getFileList( [
85 'dir' => $src->getRootStoragePath() . "/$backendRel",
86 'adviseStat' => true // avoid HEADs
87 ] );
88 if ( $srcPathsRel === null ) {
89 $this->fatalError( "Could not list files in $container." );
90 }
91 }
92
93 if ( $this->getOption( 'prestat' ) && !$this->hasOption( 'missingonly' ) ) {
94 // Build the stat cache for the destination files
95 $this->output( "\tBuilding destination stat cache..." );
96 $dstPathsRel = $dst->getFileList( [
97 'dir' => $dst->getRootStoragePath() . "/$backendRel",
98 'adviseStat' => true // avoid HEADs
99 ] );
100 if ( $dstPathsRel === null ) {
101 $this->fatalError( "Could not list files in $container." );
102 }
103 $this->statCache = [];
104 foreach ( $dstPathsRel as $dstPathRel ) {
105 $path = $dst->getRootStoragePath() . "/$backendRel/$dstPathRel";
106 $this->statCache[sha1( $path )] = $dst->getFileStat( [ 'src' => $path ] );
107 }
108 $this->output( "done [" . count( $this->statCache ) . " file(s)]\n" );
109 }
110
111 $this->output( "\tCopying file(s)...\n" );
112 $count = 0;
113 $batchPaths = [];
114 foreach ( $srcPathsRel as $srcPathRel ) {
115 // Check up on the rate file periodically to adjust the concurrency
116 if ( $rateFile && ( !$count || ( $count % 500 ) == 0 ) ) {
117 $this->setBatchSize( max( 1, (int)file_get_contents( $rateFile ) ) );
118 $this->output( "\tBatch size is now {$this->getBatchSize()}.\n" );
119 }
120 $batchPaths[$srcPathRel] = 1; // remove duplicates
121 if ( count( $batchPaths ) >= $this->getBatchSize() ) {
122 $this->copyFileBatch( array_keys( $batchPaths ), $backendRel, $src, $dst );
123 $batchPaths = []; // done
124 }
125 ++$count;
126 }
127 if ( count( $batchPaths ) ) { // left-overs
128 $this->copyFileBatch( array_keys( $batchPaths ), $backendRel, $src, $dst );
129 }
130 $this->output( "\tCopied $count file(s).\n" );
131
132 if ( $this->hasOption( 'syncviadelete' ) ) {
133 $this->output( "\tBuilding list of excess destination files..." );
134 $delPathsRel = $this->getListingDiffRel( $dst, $src, $backendRel );
135 $this->output( count( $delPathsRel ) . " file(s) need to be deleted.\n" );
136
137 $this->output( "\tDeleting file(s)...\n" );
138 $count = 0;
139 $batchPaths = [];
140 foreach ( $delPathsRel as $delPathRel ) {
141 // Check up on the rate file periodically to adjust the concurrency
142 if ( $rateFile && ( !$count || ( $count % 500 ) == 0 ) ) {
143 $this->setBatchSize( max( 1, (int)file_get_contents( $rateFile ) ) );
144 $this->output( "\tBatch size is now {$this->getBatchSize()}.\n" );
145 }
146 $batchPaths[$delPathRel] = 1; // remove duplicates
147 if ( count( $batchPaths ) >= $this->getBatchSize() ) {
148 $this->delFileBatch( array_keys( $batchPaths ), $backendRel, $dst );
149 $batchPaths = []; // done
150 }
151 ++$count;
152 }
153 if ( count( $batchPaths ) ) { // left-overs
154 $this->delFileBatch( array_keys( $batchPaths ), $backendRel, $dst );
155 }
156
157 $this->output( "\tDeleted $count file(s).\n" );
158 }
159
160 if ( $subDir != '' ) {
161 $this->output( "Finished container '$container', directory '$subDir'.\n" );
162 } else {
163 $this->output( "Finished container '$container'.\n" );
164 }
165 }
166
167 $this->output( "Done.\n" );
168 }
169
176 protected function getListingDiffRel( FileBackend $src, FileBackend $dst, $backendRel ) {
177 $srcPathsRel = $src->getFileList( [
178 'dir' => $src->getRootStoragePath() . "/$backendRel" ] );
179 if ( $srcPathsRel === null ) {
180 $this->fatalError( "Could not list files in source container." );
181 }
182 $dstPathsRel = $dst->getFileList( [
183 'dir' => $dst->getRootStoragePath() . "/$backendRel" ] );
184 if ( $dstPathsRel === null ) {
185 $this->fatalError( "Could not list files in destination container." );
186 }
187 // Get the list of destination files
188 $relFilesDstSha1 = [];
189 foreach ( $dstPathsRel as $dstPathRel ) {
190 $relFilesDstSha1[sha1( $dstPathRel )] = 1;
191 }
192 unset( $dstPathsRel ); // free
193 // Get the list of missing files
194 $missingPathsRel = [];
195 foreach ( $srcPathsRel as $srcPathRel ) {
196 if ( !isset( $relFilesDstSha1[sha1( $srcPathRel )] ) ) {
197 $missingPathsRel[] = $srcPathRel;
198 }
199 }
200 unset( $srcPathsRel ); // free
201
202 return $missingPathsRel;
203 }
204
212 protected function copyFileBatch(
213 array $srcPathsRel, $backendRel, FileBackend $src, FileBackend $dst
214 ) {
215 $ops = [];
216 $fsFiles = [];
217 $copiedRel = []; // for output message
218 $domainId = $src->getDomainId();
219
220 // Download the batch of source files into backend cache...
221 if ( $this->hasOption( 'missingonly' ) ) {
222 $srcPaths = [];
223 foreach ( $srcPathsRel as $srcPathRel ) {
224 $srcPaths[] = $src->getRootStoragePath() . "/$backendRel/$srcPathRel";
225 }
226 $t_start = microtime( true );
227 $fsFiles = $src->getLocalReferenceMulti( [ 'srcs' => $srcPaths, 'latest' => 1 ] );
228 $elapsed_ms = floor( ( microtime( true ) - $t_start ) * 1000 );
229 $this->output( "\n\tDownloaded these file(s) [{$elapsed_ms}ms]:\n\t" .
230 implode( "\n\t", $srcPaths ) . "\n\n" );
231 }
232
233 // Determine what files need to be copied over...
234 foreach ( $srcPathsRel as $srcPathRel ) {
235 $srcPath = $src->getRootStoragePath() . "/$backendRel/$srcPathRel";
236 $dstPath = $dst->getRootStoragePath() . "/$backendRel/$srcPathRel";
237 if ( $this->hasOption( 'utf8only' ) && !mb_check_encoding( $srcPath, 'UTF-8' ) ) {
238 $this->error( "$domainId: Detected illegal (non-UTF8) path for $srcPath." );
239 continue;
240 } elseif ( !$this->hasOption( 'missingonly' )
241 && $this->filesAreSame( $src, $dst, $srcPath, $dstPath )
242 ) {
243 $this->output( "\tAlready have $srcPathRel.\n" );
244 continue; // assume already copied...
245 }
246 $fsFile = array_key_exists( $srcPath, $fsFiles )
247 ? $fsFiles[$srcPath]
248 : $src->getLocalReference( [ 'src' => $srcPath, 'latest' => 1 ] );
249 if ( !$fsFile ) {
250 $src->clearCache( [ $srcPath ] );
251 if ( $src->fileExists( [ 'src' => $srcPath, 'latest' => 1 ] ) === false ) {
252 $this->error( "$domainId: File '$srcPath' was listed but does not exist." );
253 } else {
254 $this->error( "$domainId: Could not get local copy of $srcPath." );
255 }
256 continue;
257 } elseif ( !$fsFile->exists() ) {
258 // FSFileBackends just return the path for getLocalReference() and paths with
259 // illegal slashes may get normalized to a different path. This can cause the
260 // local reference to not exist...skip these broken files.
261 $this->error( "$domainId: Detected possible illegal path for $srcPath." );
262 continue;
263 }
264 $fsFiles[] = $fsFile; // keep TempFSFile objects alive as needed
265 // Note: prepare() is usually fast for key/value backends
266 $status = $dst->prepare( [ 'dir' => dirname( $dstPath ), 'bypassReadOnly' => true ] );
267 if ( !$status->isOK() ) {
268 $this->error( $status );
269 $this->fatalError( "$domainId: Could not copy $srcPath to $dstPath." );
270 }
271 $ops[] = [ 'op' => 'store',
272 'src' => $fsFile->getPath(), 'dst' => $dstPath, 'overwrite' => true ];
273 $copiedRel[] = $srcPathRel;
274 }
275
276 // Copy in the batch of source files...
277 $t_start = microtime( true );
278 $status = $dst->doQuickOperations( $ops, [ 'bypassReadOnly' => true ] );
279 if ( !$status->isOK() ) {
280 sleep( 10 ); // wait and retry copy again
281 $status = $dst->doQuickOperations( $ops, [ 'bypassReadOnly' => true ] );
282 }
283 $elapsed_ms = floor( ( microtime( true ) - $t_start ) * 1000 );
284 if ( !$status->isOK() ) {
285 $this->error( $status );
286 $this->fatalError( "$domainId: Could not copy file batch." );
287 } elseif ( count( $copiedRel ) ) {
288 $this->output( "\n\tCopied these file(s) [{$elapsed_ms}ms]:\n\t" .
289 implode( "\n\t", $copiedRel ) . "\n\n" );
290 }
291 }
292
299 protected function delFileBatch(
300 array $dstPathsRel, $backendRel, FileBackend $dst
301 ) {
302 $ops = [];
303 $deletedRel = []; // for output message
304 $domainId = $dst->getDomainId();
305
306 // Determine what files need to be copied over...
307 foreach ( $dstPathsRel as $dstPathRel ) {
308 $dstPath = $dst->getRootStoragePath() . "/$backendRel/$dstPathRel";
309 $ops[] = [ 'op' => 'delete', 'src' => $dstPath ];
310 $deletedRel[] = $dstPathRel;
311 }
312
313 // Delete the batch of source files...
314 $t_start = microtime( true );
315 $status = $dst->doQuickOperations( $ops, [ 'bypassReadOnly' => true ] );
316 if ( !$status->isOK() ) {
317 sleep( 10 ); // wait and retry copy again
318 $status = $dst->doQuickOperations( $ops, [ 'bypassReadOnly' => true ] );
319 }
320 $elapsed_ms = floor( ( microtime( true ) - $t_start ) * 1000 );
321 if ( !$status->isOK() ) {
322 $this->error( $status );
323 $this->fatalError( "$domainId: Could not delete file batch." );
324 } elseif ( count( $deletedRel ) ) {
325 $this->output( "\n\tDeleted these file(s) [{$elapsed_ms}ms]:\n\t" .
326 implode( "\n\t", $deletedRel ) . "\n\n" );
327 }
328 }
329
337 protected function filesAreSame( FileBackend $src, FileBackend $dst, $sPath, $dPath ) {
338 $skipHash = $this->hasOption( 'skiphash' );
339 $srcStat = $src->getFileStat( [ 'src' => $sPath ] );
340 $dPathSha1 = sha1( $dPath );
341 if ( $this->statCache !== null ) {
342 // All dst files are already in stat cache
343 $dstStat = $this->statCache[$dPathSha1] ?? false;
344 } else {
345 $dstStat = $dst->getFileStat( [ 'src' => $dPath ] );
346 }
347 // Initial fast checks to see if files are obviously different
348 $sameFast = (
349 is_array( $srcStat )
350 && is_array( $dstStat ) // dest exists
351 && $srcStat['size'] === $dstStat['size']
352 );
353 // More thorough checks against files
354 if ( !$sameFast ) {
355 $same = false; // no need to look farther
356 } elseif ( isset( $srcStat['md5'] ) && isset( $dstStat['md5'] ) ) {
357 // If MD5 was already in the stat info, just use it.
358 // This is useful as many objects stores can return this in object listing,
359 // so we can use it to avoid slow per-file HEADs.
360 $same = ( $srcStat['md5'] === $dstStat['md5'] );
361 } elseif ( $skipHash ) {
362 // This mode is good for copying to a backup location or resyncing clone
363 // backends in FileBackendMultiWrite (since they get writes second, they have
364 // higher timestamps). However, when copying the other way, this hits loads of
365 // false positives (possibly 100%) and wastes a bunch of time on GETs/PUTs.
366 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
367 $same = ( $srcStat['mtime'] <= $dstStat['mtime'] );
368 } else {
369 // This is the slowest method which does many per-file HEADs (unless an object
370 // store tracks SHA-1 in listings).
371 $same = ( $src->getFileSha1Base36( [ 'src' => $sPath, 'latest' => 1 ] )
372 === $dst->getFileSha1Base36( [ 'src' => $dPath, 'latest' => 1 ] ) );
373 }
374
375 return $same;
376 }
377}
378
379// @codeCoverageIgnoreStart
380$maintClass = CopyFileBackend::class;
381require_once RUN_MAINTENANCE_IF_MAIN;
382// @codeCoverageIgnoreEnd
Copy all files in one container of one backend to another.
__construct()
Default constructor.
filesAreSame(FileBackend $src, FileBackend $dst, $sPath, $dPath)
array null $statCache
(path sha1 => stat) Pre-computed dst stat entries from listings
delFileBatch(array $dstPathsRel, $backendRel, FileBackend $dst)
execute()
Do the actual work.
getListingDiffRel(FileBackend $src, FileBackend $dst, $backendRel)
copyFileBatch(array $srcPathsRel, $backendRel, FileBackend $src, FileBackend $dst)
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
error( $err, $die=0)
Throw an error to the user.
output( $out, $channel=null)
Throw some output to the user.
hasOption( $name)
Checks to see if a particular option was set.
getServiceContainer()
Returns the main service container.
getBatchSize()
Returns batch size.
addDescription( $text)
Set the description text.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
getOption( $name, $default=null)
Get an option, or return the default.
setBatchSize( $s=0)
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
Base class for all file backend classes (including multi-write backends).
prepare(array $params)
Prepare a storage directory for usage.
getFileList(array $params)
Get an iterator to list all stored files under a storage directory.
getLocalReferenceMulti(array $params)
Like getLocalReference() except it takes an array of storage paths and yields an order-preserved map ...
getFileStat(array $params)
Get quick information about a file at a storage path in the backend.
fileExists(array $params)
Check if a file exists at a storage path in the backend.
getFileSha1Base36(array $params)
Get a SHA-1 hash of the content of the file at a storage path in the backend.
getRootStoragePath()
Get the root storage path of this backend.
getDomainId()
Get the domain identifier used for this backend (possibly empty).
getLocalReference(array $params)
Returns a file system file, identical in content to the file at a storage path.
clearCache(array $paths=null)
Invalidate any in-process file stat and property cache.
doQuickOperations(array $ops, array $opts=[])
Perform a set of independent file operations on some files.