Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 201
0.00% covered (danger)
0.00%
0 / 6
CRAP
0.00% covered (danger)
0.00%
0 / 1
CopyFileBackend
0.00% covered (danger)
0.00%
0 / 198
0.00% covered (danger)
0.00%
0 / 6
3540
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
2
 execute
0.00% covered (danger)
0.00%
0 / 73
0.00% covered (danger)
0.00%
0 / 1
552
 getListingDiffRel
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
42
 copyFileBatch
0.00% covered (danger)
0.00%
0 / 55
0.00% covered (danger)
0.00%
0 / 1
272
 delFileBatch
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
30
 filesAreSame
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
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
24use MediaWiki\Status\Status;
25
26require_once __DIR__ . '/Maintenance.php';
27
28/**
29 * Copy all files in one container of one backend to another.
30 *
31 * This can also be used to re-shard the files for one backend using the
32 * config of second backend. The second backend should have the same config
33 * as the first, except for it having a different name and different sharding
34 * configuration. The backend should be made read-only while this runs.
35 * After this script finishes, the old files in the containers can be deleted.
36 *
37 * @ingroup Maintenance
38 */
39class CopyFileBackend extends Maintenance {
40    /** @var array|null (path sha1 => stat) Pre-computed dst stat entries from listings */
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 = $this->getServiceContainer()->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
168    /**
169     * @param FileBackend $src
170     * @param FileBackend $dst
171     * @param string $backendRel
172     * @return string[] (rel paths in $src minus those in $dst)
173     */
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
203    /**
204     * @param string[] $srcPathsRel
205     * @param string $backendRel
206     * @param FileBackend $src
207     * @param FileBackend $dst
208     * @return void
209     */
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' => true ] );
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' => true ];
271            $copiedRel[] = $srcPathRel;
272        }
273
274        // Copy in the batch of source files...
275        $t_start = microtime( true );
276        $status = $dst->doQuickOperations( $ops, [ 'bypassReadOnly' => true ] );
277        if ( !$status->isOK() ) {
278            sleep( 10 ); // wait and retry copy again
279            $status = $dst->doQuickOperations( $ops, [ 'bypassReadOnly' => true ] );
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
291    /**
292     * @param string[] $dstPathsRel
293     * @param string $backendRel
294     * @param FileBackend $dst
295     * @return void
296     */
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' => true ] );
314        if ( !$status->isOK() ) {
315            sleep( 10 ); // wait and retry copy again
316            $status = $dst->doQuickOperations( $ops, [ 'bypassReadOnly' => true ] );
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
328    /**
329     * @param FileBackend $src
330     * @param FileBackend $dst
331     * @param string $sPath
332     * @param string $dPath
333     * @return bool
334     */
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 )
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;