Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
0.00% |
0 / 198 |
|
0.00% |
0 / 6 |
CRAP | |
0.00% |
0 / 1 |
CopyFileBackend | |
0.00% |
0 / 198 |
|
0.00% |
0 / 6 |
3540 | |
0.00% |
0 / 1 |
__construct | |
0.00% |
0 / 13 |
|
0.00% |
0 / 1 |
2 | |||
execute | |
0.00% |
0 / 73 |
|
0.00% |
0 / 1 |
552 | |||
getListingDiffRel | |
0.00% |
0 / 18 |
|
0.00% |
0 / 1 |
42 | |||
copyFileBatch | |
0.00% |
0 / 55 |
|
0.00% |
0 / 1 |
272 | |||
delFileBatch | |
0.00% |
0 / 19 |
|
0.00% |
0 / 1 |
30 | |||
filesAreSame | |
0.00% |
0 / 20 |
|
0.00% |
0 / 1 |
72 |
1 | <?php |
2 | /** |
3 | * Copy all files in some containers of one backend to another. |
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 Maintenance |
22 | */ |
23 | |
24 | use Wikimedia\FileBackend\FileBackend; |
25 | |
26 | // @codeCoverageIgnoreStart |
27 | require_once __DIR__ . '/Maintenance.php'; |
28 | // @codeCoverageIgnoreEnd |
29 | |
30 | /** |
31 | * Copy all files in one container of one backend to another. |
32 | * |
33 | * This can also be used to re-shard the files for one backend using the |
34 | * config of second backend. The second backend should have the same config |
35 | * as the first, except for it having a different name and different sharding |
36 | * configuration. The backend should be made read-only while this runs. |
37 | * After this script finishes, the old files in the containers can be deleted. |
38 | * |
39 | * @ingroup Maintenance |
40 | */ |
41 | class CopyFileBackend extends Maintenance { |
42 | /** @var array|null (path sha1 => stat) Pre-computed dst stat entries from listings */ |
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 | |
170 | /** |
171 | * @param FileBackend $src |
172 | * @param FileBackend $dst |
173 | * @param string $backendRel |
174 | * @return string[] (rel paths in $src minus those in $dst) |
175 | */ |
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 | |
205 | /** |
206 | * @param string[] $srcPathsRel |
207 | * @param string $backendRel |
208 | * @param FileBackend $src |
209 | * @param FileBackend $dst |
210 | * @return void |
211 | */ |
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 | |
293 | /** |
294 | * @param string[] $dstPathsRel |
295 | * @param string $backendRel |
296 | * @param FileBackend $dst |
297 | * @return void |
298 | */ |
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 | |
330 | /** |
331 | * @param FileBackend $src |
332 | * @param FileBackend $dst |
333 | * @param string $sPath |
334 | * @param string $dPath |
335 | * @return bool |
336 | */ |
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; |
381 | require_once RUN_MAINTENANCE_IF_MAIN; |
382 | // @codeCoverageIgnoreEnd |