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