Merge "Simplify boolean attribute handling for Html::input in templates"
[lhc/web/wiklou.git] / maintenance / copyFileBackend.php
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 require_once __DIR__ . '/Maintenance.php';
25
26 /**
27 * Copy all files in one container of one backend to another.
28 *
29 * This can also be used to re-shard the files for one backend using the
30 * config of second backend. The second backend should have the same config
31 * as the first, except for it having a different name and different sharding
32 * configuration. The backend should be made read-only while this runs.
33 * After this script finishes, the old files in the containers can be deleted.
34 *
35 * @ingroup Maintenance
36 */
37 class CopyFileBackend extends Maintenance {
38 protected $statCache = array();
39
40 public function __construct() {
41 parent::__construct();
42 $this->mDescription = "Copy files in one backend to another.";
43 $this->addOption( 'src', 'Backend containing the source files', true, true );
44 $this->addOption( 'dst', 'Backend where files should be copied to', true, true );
45 $this->addOption( 'containers', 'Pipe separated list of containers', true, true );
46 $this->addOption( 'subdir', 'Only do items in this child directory', false, true );
47 $this->addOption( 'ratefile', 'File to check periodically for batch size', false, true );
48 $this->addOption( 'prestat', 'Stat the destination files first (try to use listings)' );
49 $this->addOption( 'skiphash', 'Skip SHA-1 sync checks for files' );
50 $this->addOption( 'missingonly', 'Only copy files missing from destination listing' );
51 $this->addOption( 'syncviadelete', 'Delete destination files missing from source listing' );
52 $this->addOption( 'utf8only', 'Skip source files that do not have valid UTF-8 names' );
53 $this->setBatchSize( 50 );
54 }
55
56 public function execute() {
57 $src = FileBackendGroup::singleton()->get( $this->getOption( 'src' ) );
58 $dst = FileBackendGroup::singleton()->get( $this->getOption( 'dst' ) );
59 $containers = explode( '|', $this->getOption( 'containers' ) );
60 $subDir = rtrim( $this->getOption( 'subdir', '' ), '/' );
61
62 $rateFile = $this->getOption( 'ratefile' );
63
64 if ( $this->hasOption( 'utf8only' ) && !extension_loaded( 'mbstring' ) ) {
65 $this->error( "Cannot check for UTF-8, mbstring extension missing.", 1 ); // die
66 }
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( array(
83 'dir' => $src->getRootStoragePath() . "/$backendRel",
84 'adviseStat' => true // avoid HEADs
85 ) );
86 if ( $srcPathsRel === null ) {
87 $this->error( "Could not list files in $container.", 1 ); // die
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( array(
95 'dir' => $dst->getRootStoragePath() . "/$backendRel",
96 'adviseStat' => true // avoid HEADs
97 ) );
98 if ( $dstPathsRel === null ) {
99 $this->error( "Could not list files in $container.", 1 ); // die
100 }
101 $this->statCache = array(); // clear
102 foreach ( $dstPathsRel as $dstPathRel ) {
103 $path = $dst->getRootStoragePath() . "/$backendRel/$dstPathRel";
104 $this->statCache[sha1( $path )] = $dst->getFileStat( array( '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 = array();
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->mBatchSize = max( 1, (int)file_get_contents( $rateFile ) );
116 $this->output( "\tBatch size is now {$this->mBatchSize}.\n" );
117 }
118 $batchPaths[$srcPathRel] = 1; // remove duplicates
119 if ( count( $batchPaths ) >= $this->mBatchSize ) {
120 $this->copyFileBatch( array_keys( $batchPaths ), $backendRel, $src, $dst );
121 $batchPaths = array(); // done
122 }
123 ++$count;
124 }
125 if ( count( $batchPaths ) ) { // left-overs
126 $this->copyFileBatch( array_keys( $batchPaths ), $backendRel, $src, $dst );
127 $batchPaths = array(); // done
128 }
129 $this->output( "\tCopied $count file(s).\n" );
130
131 if ( $this->hasOption( 'syncviadelete' ) ) {
132 $this->output( "\tBuilding list of excess destination files..." );
133 $delPathsRel = $this->getListingDiffRel( $dst, $src, $backendRel );
134 $this->output( count( $delPathsRel ) . " file(s) need to be deleted.\n" );
135
136 $this->output( "\tDeleting file(s)...\n" );
137 $count = 0;
138 $batchPaths = array();
139 foreach ( $delPathsRel as $delPathRel ) {
140 // Check up on the rate file periodically to adjust the concurrency
141 if ( $rateFile && ( !$count || ( $count % 500 ) == 0 ) ) {
142 $this->mBatchSize = max( 1, (int)file_get_contents( $rateFile ) );
143 $this->output( "\tBatch size is now {$this->mBatchSize}.\n" );
144 }
145 $batchPaths[$delPathRel] = 1; // remove duplicates
146 if ( count( $batchPaths ) >= $this->mBatchSize ) {
147 $this->delFileBatch( array_keys( $batchPaths ), $backendRel, $dst );
148 $batchPaths = array(); // done
149 }
150 ++$count;
151 }
152 if ( count( $batchPaths ) ) { // left-overs
153 $this->delFileBatch( array_keys( $batchPaths ), $backendRel, $dst );
154 $batchPaths = array(); // done
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 array (rel paths in $src minus those in $dst)
175 */
176 protected function getListingDiffRel( FileBackend $src, FileBackend $dst, $backendRel ) {
177 $srcPathsRel = $src->getFileList( array(
178 'dir' => $src->getRootStoragePath() . "/$backendRel" ) );
179 if ( $srcPathsRel === null ) {
180 $this->error( "Could not list files in source container.", 1 ); // die
181 }
182 $dstPathsRel = $dst->getFileList( array(
183 'dir' => $dst->getRootStoragePath() . "/$backendRel" ) );
184 if ( $dstPathsRel === null ) {
185 $this->error( "Could not list files in destination container.", 1 ); // die
186 }
187 // Get the list of destination files
188 $relFilesDstSha1 = array();
189 foreach ( $dstPathsRel as $dstPathRel ) {
190 $relFilesDstSha1[sha1( $dstPathRel )] = 1;
191 }
192 unset( $dstPathsRel ); // free
193 // Get the list of missing files
194 $missingPathsRel = array();
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 array $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 = array();
216 $fsFiles = array();
217 $copiedRel = array(); // for output message
218 $wikiId = $src->getWikiId();
219
220 // Download the batch of source files into backend cache...
221 if ( $this->hasOption( 'missingonly' ) ) {
222 $srcPaths = array();
223 foreach ( $srcPathsRel as $srcPathRel ) {
224 $srcPaths[] = $src->getRootStoragePath() . "/$backendRel/$srcPathRel";
225 }
226 $t_start = microtime( true );
227 $fsFiles = $src->getLocalReferenceMulti( array( 'srcs' => $srcPaths, 'latest' => 1 ) );
228 $ellapsed_ms = floor( ( microtime( true ) - $t_start ) * 1000 );
229 $this->output( "\n\tDownloaded these file(s) [{$ellapsed_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( "$wikiId: 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( array( 'src' => $srcPath, 'latest' => 1 ) );
249 if ( !$fsFile ) {
250 $src->clearCache( array( $srcPath ) );
251 if ( $src->fileExists( array( 'src' => $srcPath, 'latest' => 1 ) ) === false ) {
252 $this->error( "$wikiId: File '$srcPath' was listed but does not exist." );
253 } else {
254 $this->error( "$wikiId: 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( "$wikiId: 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( array( 'dir' => dirname( $dstPath ), 'bypassReadOnly' => 1 ) );
267 if ( !$status->isOK() ) {
268 $this->error( print_r( $status->getErrorsArray(), true ) );
269 $this->error( "$wikiId: Could not copy $srcPath to $dstPath.", 1 ); // die
270 }
271 $ops[] = array( 'op' => 'store',
272 'src' => $fsFile->getPath(), 'dst' => $dstPath, 'overwrite' => 1 );
273 $copiedRel[] = $srcPathRel;
274 }
275
276 // Copy in the batch of source files...
277 $t_start = microtime( true );
278 $status = $dst->doQuickOperations( $ops, array( 'bypassReadOnly' => 1 ) );
279 if ( !$status->isOK() ) {
280 sleep( 10 ); // wait and retry copy again
281 $status = $dst->doQuickOperations( $ops, array( 'bypassReadOnly' => 1 ) );
282 }
283 $ellapsed_ms = floor( ( microtime( true ) - $t_start ) * 1000 );
284 if ( !$status->isOK() ) {
285 $this->error( print_r( $status->getErrorsArray(), true ) );
286 $this->error( "$wikiId: Could not copy file batch.", 1 ); // die
287 } elseif ( count( $copiedRel ) ) {
288 $this->output( "\n\tCopied these file(s) [{$ellapsed_ms}ms]:\n\t" .
289 implode( "\n\t", $copiedRel ) . "\n\n" );
290 }
291 }
292
293 /**
294 * @param array $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 = array();
303 $deletedRel = array(); // for output message
304 $wikiId = $dst->getWikiId();
305
306 // Determine what files need to be copied over...
307 foreach ( $dstPathsRel as $dstPathRel ) {
308 $dstPath = $dst->getRootStoragePath() . "/$backendRel/$dstPathRel";
309 $ops[] = array( '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, array( 'bypassReadOnly' => 1 ) );
316 if ( !$status->isOK() ) {
317 sleep( 10 ); // wait and retry copy again
318 $status = $dst->doQuickOperations( $ops, array( 'bypassReadOnly' => 1 ) );
319 }
320 $ellapsed_ms = floor( ( microtime( true ) - $t_start ) * 1000 );
321 if ( !$status->isOK() ) {
322 $this->error( print_r( $status->getErrorsArray(), true ) );
323 $this->error( "$wikiId: Could not delete file batch.", 1 ); // die
324 } elseif ( count( $deletedRel ) ) {
325 $this->output( "\n\tDeleted these file(s) [{$ellapsed_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( array( 'src' => $sPath ) );
340 $dPathSha1 = sha1( $dPath );
341 $dstStat = isset( $this->statCache[$dPathSha1] )
342 ? $this->statCache[$dPathSha1]
343 : $dst->getFileStat( array( 'src' => $dPath ) );
344 return (
345 is_array( $srcStat ) // sanity check that source exists
346 && is_array( $dstStat ) // dest exists
347 && $srcStat['size'] === $dstStat['size']
348 && ( !$skipHash || $srcStat['mtime'] <= $dstStat['mtime'] )
349 && ( $skipHash || $src->getFileSha1Base36( array( 'src' => $sPath, 'latest' => 1 ) )
350 === $dst->getFileSha1Base36( array( 'src' => $dPath, 'latest' => 1 ) )
351 )
352 );
353 }
354 }
355
356 $maintClass = 'CopyFileBackend';
357 require_once RUN_MAINTENANCE_IF_MAIN;