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