3 * Sync one file backend to another based on the journal of later.
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.
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.
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
21 * @ingroup Maintenance
24 require_once( __DIR__
. '/Maintenance.php' );
27 * Maintenance script that syncs one file backend to another based on
28 * the journal of later.
30 * @ingroup Maintenance
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 );
47 public function execute() {
48 $src = FileBackendGroup
::singleton()->get( $this->getOption( 'src' ) );
50 $posDir = $this->getOption( 'posdir' );
51 $posFile = $posDir ?
$posDir . '/' . wfWikiID() : false;
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 );
58 if ( $this->hasOption( 'postime' ) ) {
59 $id = (int)$src->getJournal()->getPositionAtTime( $this->getOption( 'postime' ) );
60 $this->output( "Requested journal position is $id.\n" );
62 $id = (int)$src->getJournal()->getCurrentPosition();
63 $this->output( "Current journal position is $id.\n" );
65 if ( file_put_contents( $posFile, $id, LOCK_EX
) !== false ) {
66 $this->output( "Saved journal position file.\n" );
68 $this->output( "Could not save journal position file.\n" );
70 if ( $this->isQuiet() ) {
71 print $id; // give a single machine-readable number
76 if ( !$this->hasOption( 'dst' ) ) {
77 $this->error( "Param dst required!", 1 );
79 $dst = FileBackendGroup
::singleton()->get( $this->getOption( 'dst' ) );
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 ) )
86 ++
$start; // we already did this ID, start with the next one
87 $startFromPosFile = true;
89 $startFromPosFile = false;
91 $end = $this->getOption( 'end', INF
);
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" );
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
);
106 // Actually sync the dest backend with the reference backend
107 $lastOKPos = $this->syncBackends( $src, $dst, $start, $end, $callback );
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" );
114 $this->output( "Could not update journal position file.\n" );
118 if ( $lastOKPos === false ) {
120 $this->output( "No journal entries found.\n" );
122 $this->output( "No new journal entries found.\n" );
125 $this->output( "Stopped synchronization at journal position $lastOKPos.\n" );
128 if ( $this->isQuiet() ) {
129 print $lastOKPos; // give a single machine-readable number
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).
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
144 protected function syncBackends(
145 FileBackend
$src, FileBackend
$dst, $start, $end, Closure
$callback
147 $lastOKPos = 0; // failed
148 $first = true; // first batch
150 if ( $start > $end ) { // sanity
151 $this->error( "Error: given starting ID greater than ending ID.", 1 );
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" );
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
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
171 $lastPosInBatch = $entry['id'];
174 $status = $this->syncFileBatch( array_keys( $pathsInBatch ), $src, $dst );
175 if ( $status->isOK() ) {
176 $lastOKPos = max( $lastOKPos, $lastPosInBatch );
177 $callback( $lastOKPos ); // update position file
179 $this->error( print_r( $status->getErrorsArray(), true ) );
180 break; // no gaps; everything up to $lastPos must be OK
184 $this->output( "End of journal entries.\n" );
186 } while ( $start && $start <= $end );
192 * Sync particular files of backend $src to the corresponding $dst backend files
194 * @param $paths Array
195 * @param $src FileBackend
196 * @param $dst FileBackend
199 protected function syncFileBatch( array $paths, FileBackend
$src, FileBackend
$dst ) {
200 $status = Status
::newGood();
201 if ( !count( $paths ) ) {
202 return $status; // nothing to do
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 );
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() ) {
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
226 // Note: getLocalReference() is fast for FS backends
227 $fsFile = $src->getLocalReference( array( 'src' => $sPath, 'latest' => 1 ) );
229 $this->error( "Unable to sync '$dPath': could not get local copy." );
230 $status->fatal( 'backend-fail-internal', $src->getName() );
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() ) {
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 );
245 $this->error( "Unable to sync '$dPath': could not stat file." );
246 $status->fatal( 'backend-fail-internal', $src->getName() );
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 ) );
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" );
267 * Substitute the backend name of storage paths with that of a given one
269 * @param $paths Array|string List of paths or single string path
270 * @return Array|string
272 protected function replaceNamePaths( $paths, FileBackend
$backend ) {
274 '!^mwstore://([^/]+)!',
275 StringUtils
::escapeRegexReplacement( "mwstore://" . $backend->getName() ),
276 $paths // string or array
280 protected function filesAreSame( FileBackend
$src, FileBackend
$dst, $sPath, $dPath ) {
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 ) )
291 $maintClass = "SyncFileBackend";
292 require_once( RUN_MAINTENANCE_IF_MAIN
);