phpcs: More require/include is not a function
[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( 'utf8only', 'Skip source files that do not have valid UTF-8 names' );
52 $this->setBatchSize( 50 );
53 }
54
55 public function execute() {
56 $src = FileBackendGroup::singleton()->get( $this->getOption( 'src' ) );
57 $dst = FileBackendGroup::singleton()->get( $this->getOption( 'dst' ) );
58 $containers = explode( '|', $this->getOption( 'containers' ) );
59 $subDir = $this->getOption( rtrim( 'subdir', '/' ), '' );
60
61 $rateFile = $this->getOption( 'ratefile' );
62
63 if ( $this->hasOption( 'utf8only' ) && !extension_loaded( 'mbstring' ) ) {
64 $this->error( "Cannot check for UTF-8, mbstring extension missing.", 1 ); // die
65 }
66
67 $count = 0;
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 $srcPathsRel = $src->getFileList( array(
78 'dir' => $src->getRootStoragePath() . "/$backendRel",
79 'adviseStat' => !$this->hasOption( 'missingonly' ) // avoid HEADs
80 ) );
81 if ( $srcPathsRel === null ) {
82 $this->error( "Could not list files in $container.", 1 ); // die
83 }
84
85 if ( $this->hasOption( 'missingonly' ) ) {
86 $dstPathsRel = $dst->getFileList( array(
87 'dir' => $dst->getRootStoragePath() . "/$backendRel" ) );
88 if ( $dstPathsRel === null ) {
89 $this->error( "Could not list files in $container.", 1 ); // die
90 }
91 // Get the list of destination files
92 $relFilesDstSha1 = array();
93 foreach ( $dstPathsRel as $dstPathRel ) {
94 $relFilesDstSha1[sha1( $dstPathRel )] = 1;
95 }
96 unset( $dstPathsRel ); // free
97 // Get the list of missing files
98 $missingPathsRel = array();
99 foreach ( $srcPathsRel as $srcPathRel ) {
100 if ( !isset( $relFilesDstSha1[sha1( $srcPathRel )] ) ) {
101 $missingPathsRel[] = $srcPathRel;
102 }
103 }
104 unset( $srcPathsRel ); // free
105 // Only copy the missing files over in the next loop
106 $srcPathsRel = $missingPathsRel;
107 $this->output( count( $srcPathsRel ) . " file(s) need to be copied.\n" );
108 } elseif ( $this->getOption( 'prestat' ) ) {
109 // Build the stat cache for the destination files
110 $this->output( "Building destination stat cache..." );
111 $dstPathsRel = $dst->getFileList( array(
112 'dir' => $dst->getRootStoragePath() . "/$backendRel",
113 'adviseStat' => true // avoid HEADs
114 ) );
115 if ( $dstPathsRel === null ) {
116 $this->error( "Could not list files in $container.", 1 ); // die
117 }
118 $this->statCache = array(); // clear
119 foreach ( $dstPathsRel as $dstPathRel ) {
120 $path = $dst->getRootStoragePath() . "/$backendRel/$dstPathRel";
121 $this->statCache[sha1( $path )] = $dst->getFileStat( array( 'src' => $path ) );
122 }
123 $this->output( "done [" . count( $this->statCache ) . " file(s)]\n" );
124 }
125
126 $batchPaths = array();
127 foreach ( $srcPathsRel as $srcPathRel ) {
128 // Check up on the rate file periodically to adjust the concurrency
129 if ( $rateFile && ( !$count || ( $count % 500 ) == 0 ) ) {
130 $this->mBatchSize = max( 1, (int)file_get_contents( $rateFile ) );
131 $this->output( "Batch size is now {$this->mBatchSize}.\n" );
132 }
133 $batchPaths[$srcPathRel] = 1; // remove duplicates
134 if ( count( $batchPaths ) >= $this->mBatchSize ) {
135 $this->copyFileBatch( array_keys( $batchPaths ), $backendRel, $src, $dst );
136 $batchPaths = array(); // done
137 }
138 ++$count;
139 }
140 if ( count( $batchPaths ) ) { // left-overs
141 $this->copyFileBatch( array_keys( $batchPaths ), $backendRel, $src, $dst );
142 $batchPaths = array(); // done
143 }
144
145 if ( $subDir != '' ) {
146 $this->output( "Finished container '$container', directory '$subDir'.\n" );
147 } else {
148 $this->output( "Finished container '$container'.\n" );
149 }
150 }
151
152 $this->output( "Done [$count file(s)].\n" );
153 }
154
155 protected function copyFileBatch(
156 array $srcPathsRel, $backendRel, FileBackend $src, FileBackend $dst
157 ) {
158 $ops = array();
159 $fsFiles = array();
160 $copiedRel = array(); // for output message
161 $wikiId = $src->getWikiId();
162
163 // Download the batch of source files into backend cache...
164 if ( $this->hasOption( 'missingonly' ) ) {
165 $srcPaths = array();
166 foreach ( $srcPathsRel as $srcPathRel ) {
167 $srcPaths[] = $src->getRootStoragePath() . "/$backendRel/$srcPathRel";
168 }
169 $t_start = microtime( true );
170 $fsFiles = $src->getLocalReferenceMulti( array( 'srcs' => $srcPaths, 'latest' => 1 ) );
171 $ellapsed_ms = floor( ( microtime( true ) - $t_start ) * 1000 );
172 $this->output( "\nDownloaded these file(s) [{$ellapsed_ms}ms]:\n" .
173 implode( "\n", $srcPaths ) . "\n\n" );
174 }
175
176 // Determine what files need to be copied over...
177 foreach ( $srcPathsRel as $srcPathRel ) {
178 $srcPath = $src->getRootStoragePath() . "/$backendRel/$srcPathRel";
179 $dstPath = $dst->getRootStoragePath() . "/$backendRel/$srcPathRel";
180 if ( $this->hasOption( 'utf8only' ) && !mb_check_encoding( $srcPath, 'UTF-8' ) ) {
181 $this->error( "$wikiId: Detected illegal (non-UTF8) path for $srcPath." );
182 continue;
183 } elseif ( !$this->hasOption( 'missingonly' )
184 && $this->filesAreSame( $src, $dst, $srcPath, $dstPath ) )
185 {
186 $this->output( "Already have $srcPathRel.\n" );
187 continue; // assume already copied...
188 }
189 $fsFile = array_key_exists( $srcPath, $fsFiles )
190 ? $fsFiles[$srcPath]
191 : $src->getLocalReference( array( 'src' => $srcPath, 'latest' => 1 ) );
192 if ( !$fsFile ) {
193 $src->clearCache( array( $srcPath ) );
194 if ( $src->fileExists( array( 'src' => $srcPath, 'latest' => 1 ) ) === false ) {
195 $this->error( "$wikiId: File '$srcPath' was listed but does not exist." );
196 } else {
197 $this->error( "$wikiId: Could not get local copy of $srcPath." );
198 }
199 continue;
200 } elseif ( !$fsFile->exists() ) {
201 // FSFileBackends just return the path for getLocalReference() and paths with
202 // illegal slashes may get normalized to a different path. This can cause the
203 // local reference to not exist...skip these broken files.
204 $this->error( "$wikiId: Detected possible illegal path for $srcPath." );
205 continue;
206 }
207 $fsFiles[] = $fsFile; // keep TempFSFile objects alive as needed
208 // Note: prepare() is usually fast for key/value backends
209 $status = $dst->prepare( array( 'dir' => dirname( $dstPath ), 'bypassReadOnly' => 1 ) );
210 if ( !$status->isOK() ) {
211 $this->error( print_r( $status->getErrorsArray(), true ) );
212 $this->error( "$wikiId: Could not copy $srcPath to $dstPath.", 1 ); // die
213 }
214 $ops[] = array( 'op' => 'store',
215 'src' => $fsFile->getPath(), 'dst' => $dstPath, 'overwrite' => 1 );
216 $copiedRel[] = $srcPathRel;
217 }
218
219 // Copy in the batch of source files...
220 $t_start = microtime( true );
221 $status = $dst->doQuickOperations( $ops, array( 'bypassReadOnly' => 1 ) );
222 if ( !$status->isOK() ) {
223 sleep( 10 ); // wait and retry copy again
224 $status = $dst->doQuickOperations( $ops, array( 'bypassReadOnly' => 1 ) );
225 }
226 $ellapsed_ms = floor( ( microtime( true ) - $t_start ) * 1000 );
227 if ( !$status->isOK() ) {
228 $this->error( print_r( $status->getErrorsArray(), true ) );
229 $this->error( "$wikiId: Could not copy file batch.", 1 ); // die
230 } elseif ( count( $copiedRel ) ) {
231 $this->output( "\nCopied these file(s) [{$ellapsed_ms}ms]:\n" .
232 implode( "\n", $copiedRel ) . "\n\n" );
233 }
234 }
235
236 protected function filesAreSame( FileBackend $src, FileBackend $dst, $sPath, $dPath ) {
237 $skipHash = $this->hasOption( 'skiphash' );
238 $srcStat = $src->getFileStat( array( 'src' => $sPath ) );
239 $dPathSha1 = sha1( $dPath );
240 $dstStat = isset( $this->statCache[$dPathSha1] )
241 ? $this->statCache[$dPathSha1]
242 : $dst->getFileStat( array( 'src' => $dPath ) );
243 return (
244 is_array( $srcStat ) // sanity check that source exists
245 && is_array( $dstStat ) // dest exists
246 && $srcStat['size'] === $dstStat['size']
247 && ( !$skipHash || $srcStat['mtime'] <= $dstStat['mtime'] )
248 && ( $skipHash || $src->getFileSha1Base36( array( 'src' => $sPath, 'latest' => 1 ) )
249 === $dst->getFileSha1Base36( array( 'src' => $dPath, 'latest' => 1 ) )
250 )
251 );
252 }
253 }
254
255 $maintClass = 'CopyFileBackend';
256 require_once RUN_MAINTENANCE_IF_MAIN;