Merge "Fix wfWaitForSlaves() so the $wiki parameter actually works correctly"
[lhc/web/wiklou.git] / maintenance / syncFileBackend.php
1 <?php
2 /**
3 * Sync one file backend to another based on the journal of later.
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 * Maintenance script that syncs one file backend to another based on
28 * the journal of later.
29 *
30 * @ingroup Maintenance
31 */
32 class SyncFileBackend extends Maintenance {
33 public function __construct() {
34 parent::__construct();
35 $this->mDescription = "Sync one file backend with another using the journal";
36 $this->addOption( 'src', 'Name of backend to sync from', true, true );
37 $this->addOption( 'dst', 'Name of destination backend to sync', false, true );
38 $this->addOption( 'start', 'Starting journal ID', false, true );
39 $this->addOption( 'end', 'Ending journal ID', false, true );
40 $this->addOption( 'posdir', 'Directory to read/record journal positions', false, true );
41 $this->addOption( 'posdump', 'Just dump current journal position into the position dir.' );
42 $this->addOption( 'postime', 'For position dumps, get the ID at this time', false, true );
43 $this->addOption( 'verbose', 'Verbose mode', false, false, 'v' );
44 $this->setBatchSize( 50 );
45 }
46
47 public function execute() {
48 $src = FileBackendGroup::singleton()->get( $this->getOption( 'src' ) );
49
50 $posDir = $this->getOption( 'posdir' );
51 $posFile = $posDir ? $posDir . '/' . wfWikiID() : false;
52
53 if ( $this->hasOption( 'posdump' ) ) {
54 // Just dump the current position into the specified position dir
55 if ( !$this->hasOption( 'posdir' ) ) {
56 $this->error( "Param posdir required!", 1 );
57 }
58 if ( $this->hasOption( 'postime' ) ) {
59 $id = (int)$src->getJournal()->getPositionAtTime( $this->getOption( 'postime' ) );
60 $this->output( "Requested journal position is $id.\n" );
61 } else {
62 $id = (int)$src->getJournal()->getCurrentPosition();
63 $this->output( "Current journal position is $id.\n" );
64 }
65 if ( file_put_contents( $posFile, $id, LOCK_EX ) !== false ) {
66 $this->output( "Saved journal position file.\n" );
67 } else {
68 $this->output( "Could not save journal position file.\n" );
69 }
70 if ( $this->isQuiet() ) {
71 print $id; // give a single machine-readable number
72 }
73 return;
74 }
75
76 if ( !$this->hasOption( 'dst' ) ) {
77 $this->error( "Param dst required!", 1 );
78 }
79 $dst = FileBackendGroup::singleton()->get( $this->getOption( 'dst' ) );
80
81 $start = $this->getOption( 'start', 0 );
82 if ( !$start && $posFile && is_dir( $posDir ) ) {
83 $start = is_file( $posFile )
84 ? (int)trim( file_get_contents( $posFile ) )
85 : 0;
86 ++$start; // we already did this ID, start with the next one
87 $startFromPosFile = true;
88 } else {
89 $startFromPosFile = false;
90 }
91 $end = $this->getOption( 'end', INF );
92
93 $this->output( "Synchronizing backend '{$dst->getName()}' to '{$src->getName()}'...\n" );
94 $this->output( "Starting journal position is $start.\n" );
95 if ( is_finite( $end ) ) {
96 $this->output( "Ending journal position is $end.\n" );
97 }
98
99 // Periodically update the position file
100 $callback = function( $pos ) use ( $startFromPosFile, $posFile, $start ) {
101 if ( $startFromPosFile && $pos >= $start ) { // successfully advanced
102 file_put_contents( $posFile, $pos, LOCK_EX );
103 }
104 };
105
106 // Actually sync the dest backend with the reference backend
107 $lastOKPos = $this->syncBackends( $src, $dst, $start, $end, $callback );
108
109 // Update the sync position file
110 if ( $startFromPosFile && $lastOKPos >= $start ) { // successfully advanced
111 if ( file_put_contents( $posFile, $lastOKPos, LOCK_EX ) !== false ) {
112 $this->output( "Updated journal position file.\n" );
113 } else {
114 $this->output( "Could not update journal position file.\n" );
115 }
116 }
117
118 if ( $lastOKPos === false ) {
119 if ( !$start ) {
120 $this->output( "No journal entries found.\n" );
121 } else {
122 $this->output( "No new journal entries found.\n" );
123 }
124 } else {
125 $this->output( "Stopped synchronization at journal position $lastOKPos.\n" );
126 }
127
128 if ( $this->isQuiet() ) {
129 print $lastOKPos; // give a single machine-readable number
130 }
131 }
132
133 /**
134 * Sync $dst backend to $src backend based on the $src logs given after $start.
135 * Returns the journal entry ID this advanced to and handled (inclusive).
136 *
137 * @param $src FileBackend
138 * @param $dst FileBackend
139 * @param $start integer Starting journal position
140 * @param $end integer Starting journal position
141 * @param $callback Closure Callback to update any position file
142 * @return integer|false Journal entry ID or false if there are none
143 */
144 protected function syncBackends(
145 FileBackend $src, FileBackend $dst, $start, $end, Closure $callback
146 ) {
147 $lastOKPos = 0; // failed
148 $first = true; // first batch
149
150 if ( $start > $end ) { // sanity
151 $this->error( "Error: given starting ID greater than ending ID.", 1 );
152 }
153
154 do {
155 $limit = min( $this->mBatchSize, $end - $start + 1 ); // don't go pass ending ID
156 $this->output( "Doing id $start to " . ( $start + $limit - 1 ) . "...\n" );
157
158 $entries = $src->getJournal()->getChangeEntries( $start, $limit, $next );
159 $start = $next; // start where we left off next time
160 if ( $first && !count( $entries ) ) {
161 return false; // nothing to do
162 }
163 $first = false;
164
165 $lastPosInBatch = 0;
166 $pathsInBatch = array(); // changed paths
167 foreach ( $entries as $entry ) {
168 if ( $entry['op'] !== 'null' ) { // null ops are just for reference
169 $pathsInBatch[$entry['path']] = 1; // remove duplicates
170 }
171 $lastPosInBatch = $entry['id'];
172 }
173
174 $status = $this->syncFileBatch( array_keys( $pathsInBatch ), $src, $dst );
175 if ( $status->isOK() ) {
176 $lastOKPos = max( $lastOKPos, $lastPosInBatch );
177 $callback( $lastOKPos ); // update position file
178 } else {
179 $this->error( print_r( $status->getErrorsArray(), true ) );
180 break; // no gaps; everything up to $lastPos must be OK
181 }
182
183 if ( !$start ) {
184 $this->output( "End of journal entries.\n" );
185 }
186 } while ( $start && $start <= $end );
187
188 return $lastOKPos;
189 }
190
191 /**
192 * Sync particular files of backend $src to the corresponding $dst backend files
193 *
194 * @param $paths Array
195 * @param $src FileBackend
196 * @param $dst FileBackend
197 * @return Status
198 */
199 protected function syncFileBatch( array $paths, FileBackend $src, FileBackend $dst ) {
200 $status = Status::newGood();
201 if ( !count( $paths ) ) {
202 return $status; // nothing to do
203 }
204
205 // Source: convert internal backend names (FileBackendMultiWrite) to the public one
206 $sPaths = $this->replaceNamePaths( $paths, $src );
207 // Destination: get corresponding path name
208 $dPaths = $this->replaceNamePaths( $paths, $dst );
209
210 // Lock the live backend paths from modification
211 $sLock = $src->getScopedFileLocks( $sPaths, LockManager::LOCK_UW, $status );
212 $eLock = $dst->getScopedFileLocks( $dPaths, LockManager::LOCK_EX, $status );
213 if ( !$status->isOK() ) {
214 return $status;
215 }
216
217 $ops = array();
218 $fsFiles = array();
219 foreach ( $sPaths as $i => $sPath ) {
220 $dPath = $dPaths[$i]; // destination
221 $sExists = $src->fileExists( array( 'src' => $sPath, 'latest' => 1 ) );
222 if ( $sExists === true ) { // exists in source
223 if ( $this->filesAreSame( $src, $dst, $sPath, $dPath ) ) {
224 continue; // avoid local copies for non-FS backends
225 }
226 // Note: getLocalReference() is fast for FS backends
227 $fsFile = $src->getLocalReference( array( 'src' => $sPath, 'latest' => 1 ) );
228 if ( !$fsFile ) {
229 $this->error( "Unable to sync '$dPath': could not get local copy." );
230 $status->fatal( 'backend-fail-internal', $src->getName() );
231 return $status;
232 }
233 $fsFiles[] = $fsFile; // keep TempFSFile objects alive as needed
234 // Note: prepare() is usually fast for key/value backends
235 $status->merge( $dst->prepare( array(
236 'dir' => dirname( $dPath ), 'bypassReadOnly' => 1 ) ) );
237 if ( !$status->isOK() ) {
238 return $status;
239 }
240 $ops[] = array( 'op' => 'store',
241 'src' => $fsFile->getPath(), 'dst' => $dPath, 'overwrite' => 1 );
242 } elseif ( $sExists === false ) { // does not exist in source
243 $ops[] = array( 'op' => 'delete', 'src' => $dPath, 'ignoreMissingSource' => 1 );
244 } else { // error
245 $this->error( "Unable to sync '$dPath': could not stat file." );
246 $status->fatal( 'backend-fail-internal', $src->getName() );
247 return $status;
248 }
249 }
250
251 $t_start = microtime( true );
252 $status = $dst->doQuickOperations( $ops, array( 'bypassReadOnly' => 1 ) );
253 if ( !$status->isOK() ) {
254 sleep( 10 ); // wait and retry copy again
255 $status = $dst->doQuickOperations( $ops, array( 'bypassReadOnly' => 1 ) );
256 }
257 $ellapsed_ms = floor( ( microtime( true ) - $t_start ) * 1000 );
258 if ( $status->isOK() && $this->getOption( 'verbose' ) ) {
259 $this->output( "Synchronized these file(s) [{$ellapsed_ms}ms]:\n" .
260 implode( "\n", $dPaths ) . "\n" );
261 }
262
263 return $status;
264 }
265
266 /**
267 * Substitute the backend name of storage paths with that of a given one
268 *
269 * @param $paths Array|string List of paths or single string path
270 * @return Array|string
271 */
272 protected function replaceNamePaths( $paths, FileBackend $backend ) {
273 return preg_replace(
274 '!^mwstore://([^/]+)!',
275 StringUtils::escapeRegexReplacement( "mwstore://" . $backend->getName() ),
276 $paths // string or array
277 );
278 }
279
280 protected function filesAreSame( FileBackend $src, FileBackend $dst, $sPath, $dPath ) {
281 return (
282 ( $src->getFileSize( array( 'src' => $sPath ) )
283 === $dst->getFileSize( array( 'src' => $dPath ) ) // short-circuit
284 ) && ( $src->getFileSha1Base36( array( 'src' => $sPath ) )
285 === $dst->getFileSha1Base36( array( 'src' => $dPath ) )
286 )
287 );
288 }
289 }
290
291 $maintClass = "SyncFileBackend";
292 require_once( RUN_MAINTENANCE_IF_MAIN );