MediaWiki  1.28.0
syncFileBackend.php
Go to the documentation of this file.
1 <?php
24 require_once __DIR__ . '/Maintenance.php';
25 
33  public function __construct() {
34  parent::__construct();
35  $this->addDescription( '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 
75  return;
76  }
77 
78  if ( !$this->hasOption( 'dst' ) ) {
79  $this->error( "Param dst required!", 1 );
80  }
81  $dst = FileBackendGroup::singleton()->get( $this->getOption( 'dst' ) );
82 
83  $start = $this->getOption( 'start', 0 );
84  if ( !$start && $posFile && is_dir( $posDir ) ) {
85  $start = is_file( $posFile )
86  ? (int)trim( file_get_contents( $posFile ) )
87  : 0;
88  ++$start; // we already did this ID, start with the next one
89  $startFromPosFile = true;
90  } else {
91  $startFromPosFile = false;
92  }
93 
94  if ( $this->hasOption( 'backoff' ) ) {
95  $time = time() - $this->getOption( 'backoff', 0 );
96  $end = (int)$src->getJournal()->getPositionAtTime( $time );
97  } else {
98  $end = $this->getOption( 'end', INF );
99  }
100 
101  $this->output( "Synchronizing backend '{$dst->getName()}' to '{$src->getName()}'...\n" );
102  $this->output( "Starting journal position is $start.\n" );
103  if ( is_finite( $end ) ) {
104  $this->output( "Ending journal position is $end.\n" );
105  }
106 
107  // Periodically update the position file
108  $callback = function ( $pos ) use ( $startFromPosFile, $posFile, $start ) {
109  if ( $startFromPosFile && $pos >= $start ) { // successfully advanced
110  file_put_contents( $posFile, $pos, LOCK_EX );
111  }
112  };
113 
114  // Actually sync the dest backend with the reference backend
115  $lastOKPos = $this->syncBackends( $src, $dst, $start, $end, $callback );
116 
117  // Update the sync position file
118  if ( $startFromPosFile && $lastOKPos >= $start ) { // successfully advanced
119  if ( file_put_contents( $posFile, $lastOKPos, LOCK_EX ) !== false ) {
120  $this->output( "Updated journal position file.\n" );
121  } else {
122  $this->output( "Could not update journal position file.\n" );
123  }
124  }
125 
126  if ( $lastOKPos === false ) {
127  if ( !$start ) {
128  $this->output( "No journal entries found.\n" );
129  } else {
130  $this->output( "No new journal entries found.\n" );
131  }
132  } else {
133  $this->output( "Stopped synchronization at journal position $lastOKPos.\n" );
134  }
135 
136  if ( $this->isQuiet() ) {
137  print $lastOKPos; // give a single machine-readable number
138  }
139  }
140 
152  protected function syncBackends(
153  FileBackend $src, FileBackend $dst, $start, $end, Closure $callback
154  ) {
155  $lastOKPos = 0; // failed
156  $first = true; // first batch
157 
158  if ( $start > $end ) { // sanity
159  $this->error( "Error: given starting ID greater than ending ID.", 1 );
160  }
161 
162  $next = null;
163  do {
164  $limit = min( $this->mBatchSize, $end - $start + 1 ); // don't go pass ending ID
165  $this->output( "Doing id $start to " . ( $start + $limit - 1 ) . "...\n" );
166 
167  $entries = $src->getJournal()->getChangeEntries( $start, $limit, $next );
168  $start = $next; // start where we left off next time
169  if ( $first && !count( $entries ) ) {
170  return false; // nothing to do
171  }
172  $first = false;
173 
174  $lastPosInBatch = 0;
175  $pathsInBatch = []; // changed paths
176  foreach ( $entries as $entry ) {
177  if ( $entry['op'] !== 'null' ) { // null ops are just for reference
178  $pathsInBatch[$entry['path']] = 1; // remove duplicates
179  }
180  $lastPosInBatch = $entry['id'];
181  }
182 
183  $status = $this->syncFileBatch( array_keys( $pathsInBatch ), $src, $dst );
184  if ( $status->isOK() ) {
185  $lastOKPos = max( $lastOKPos, $lastPosInBatch );
186  $callback( $lastOKPos ); // update position file
187  } else {
188  $this->error( print_r( $status->getErrorsArray(), true ) );
189  break; // no gaps; everything up to $lastPos must be OK
190  }
191 
192  if ( !$start ) {
193  $this->output( "End of journal entries.\n" );
194  }
195  } while ( $start && $start <= $end );
196 
197  return $lastOKPos;
198  }
199 
208  protected function syncFileBatch( array $paths, FileBackend $src, FileBackend $dst ) {
210  if ( !count( $paths ) ) {
211  return $status; // nothing to do
212  }
213 
214  // Source: convert internal backend names (FileBackendMultiWrite) to the public one
215  $sPaths = $this->replaceNamePaths( $paths, $src );
216  // Destination: get corresponding path name
217  $dPaths = $this->replaceNamePaths( $paths, $dst );
218 
219  // Lock the live backend paths from modification
220  $sLock = $src->getScopedFileLocks( $sPaths, LockManager::LOCK_UW, $status );
221  $eLock = $dst->getScopedFileLocks( $dPaths, LockManager::LOCK_EX, $status );
222  if ( !$status->isOK() ) {
223  return $status;
224  }
225 
226  $src->preloadFileStat( [ 'srcs' => $sPaths, 'latest' => 1 ] );
227  $dst->preloadFileStat( [ 'srcs' => $dPaths, 'latest' => 1 ] );
228 
229  $ops = [];
230  $fsFiles = [];
231  foreach ( $sPaths as $i => $sPath ) {
232  $dPath = $dPaths[$i]; // destination
233  $sExists = $src->fileExists( [ 'src' => $sPath, 'latest' => 1 ] );
234  if ( $sExists === true ) { // exists in source
235  if ( $this->filesAreSame( $src, $dst, $sPath, $dPath ) ) {
236  continue; // avoid local copies for non-FS backends
237  }
238  // Note: getLocalReference() is fast for FS backends
239  $fsFile = $src->getLocalReference( [ 'src' => $sPath, 'latest' => 1 ] );
240  if ( !$fsFile ) {
241  $this->error( "Unable to sync '$dPath': could not get local copy." );
242  $status->fatal( 'backend-fail-internal', $src->getName() );
243 
244  return $status;
245  }
246  $fsFiles[] = $fsFile; // keep TempFSFile objects alive as needed
247  // Note: prepare() is usually fast for key/value backends
248  $status->merge( $dst->prepare( [
249  'dir' => dirname( $dPath ), 'bypassReadOnly' => 1 ] ) );
250  if ( !$status->isOK() ) {
251  return $status;
252  }
253  $ops[] = [ 'op' => 'store',
254  'src' => $fsFile->getPath(), 'dst' => $dPath, 'overwrite' => 1 ];
255  } elseif ( $sExists === false ) { // does not exist in source
256  $ops[] = [ 'op' => 'delete', 'src' => $dPath, 'ignoreMissingSource' => 1 ];
257  } else { // error
258  $this->error( "Unable to sync '$dPath': could not stat file." );
259  $status->fatal( 'backend-fail-internal', $src->getName() );
260 
261  return $status;
262  }
263  }
264 
265  $t_start = microtime( true );
266  $status = $dst->doQuickOperations( $ops, [ 'bypassReadOnly' => 1 ] );
267  if ( !$status->isOK() ) {
268  sleep( 10 ); // wait and retry copy again
269  $status = $dst->doQuickOperations( $ops, [ 'bypassReadOnly' => 1 ] );
270  }
271  $elapsed_ms = floor( ( microtime( true ) - $t_start ) * 1000 );
272  if ( $status->isOK() && $this->getOption( 'verbose' ) ) {
273  $this->output( "Synchronized these file(s) [{$elapsed_ms}ms]:\n" .
274  implode( "\n", $dPaths ) . "\n" );
275  }
276 
277  return $status;
278  }
279 
287  protected function replaceNamePaths( $paths, FileBackend $backend ) {
288  return preg_replace(
289  '!^mwstore://([^/]+)!',
290  StringUtils::escapeRegexReplacement( "mwstore://" . $backend->getName() ),
291  $paths // string or array
292  );
293  }
294 
295  protected function filesAreSame( FileBackend $src, FileBackend $dst, $sPath, $dPath ) {
296  return (
297  ( $src->getFileSize( [ 'src' => $sPath ] )
298  === $dst->getFileSize( [ 'src' => $dPath ] ) // short-circuit
299  ) && ( $src->getFileSha1Base36( [ 'src' => $sPath ] )
300  === $dst->getFileSha1Base36( [ 'src' => $dPath ] )
301  )
302  );
303  }
304 }
305 
306 $maintClass = "SyncFileBackend";
307 require_once RUN_MAINTENANCE_IF_MAIN;
the array() calling protocol came about after MediaWiki 1.4rc1.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Maintenance script that syncs one file backend to another based on the journal of later...
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: maintenance.txt:39
getName()
Get the unique backend name.
hasOption($name)
Checks to see if a particular param exists.
getScopedFileLocks(array $paths, $type, StatusValue $status, $timeout=0)
Lock the files at the given storage paths in the backend.
static escapeRegexReplacement($string)
Escape a string to make it suitable for inclusion in a preg_replace() replacement parameter...
require_once RUN_MAINTENANCE_IF_MAIN
Definition: maintenance.txt:50
syncBackends(FileBackend $src, FileBackend $dst, $start, $end, Closure $callback)
Sync $dst backend to $src backend based on the $src logs given after $start.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition: hooks.txt:1936
addOption($name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
const LOCK_UW
Definition: LockManager.php:69
const LOCK_EX
Definition: LockManager.php:70
fileExists(array $params)
Check if a file exists at a storage path in the backend.
getFileSha1Base36(array $params)
Get a SHA-1 hash of the file at a storage path in the backend.
static newGood($value=null)
Factory function for good results.
Definition: StatusValue.php:76
getFileSize(array $params)
Get the size (bytes) of a file at a storage path in the backend.
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
addDescription($text)
Set the description text.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
doQuickOperations(array $ops, array $opts=[])
Perform a set of independent file operations on some files.
prepare(array $params)
Prepare a storage directory for usage.
getOption($name, $default=null)
Get an option, or return the default.
output($out, $channel=null)
Throw some output to the user.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
getJournal()
Get the file journal object for this backend.
error($err, $die=0)
Throw an error to the user.
Base class for all file backend classes (including multi-write backends).
Definition: FileBackend.php:93
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object to manipulate or replace but no entry for that model exists in $wgContentHandlers if desired whether it is OK to use $contentModel on $title Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok inclusive $limit
Definition: hooks.txt:1046
syncFileBatch(array $paths, FileBackend $src, FileBackend $dst)
Sync particular files of backend $src to the corresponding $dst backend files.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
Definition: hooks.txt:1046
replaceNamePaths($paths, FileBackend $backend)
Substitute the backend name of storage paths with that of a given one.
$maintClass
setBatchSize($s=0)
Set the batch size.
preloadFileStat(array $params)
Preload file stat information (concurrently if possible) into in-process cache.
getLocalReference(array $params)
Returns a file system file, identical to the file at a storage path.
filesAreSame(FileBackend $src, FileBackend $dst, $sPath, $dPath)
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition: hooks.txt:1749