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