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