MediaWiki  1.23.13
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->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 
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 
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  $src->preloadFileStat( array( 'srcs' => $sPaths, 'latest' => 1 ) );
225  $dst->preloadFileStat( array( 'srcs' => $dPaths, 'latest' => 1 ) );
226 
227  $ops = array();
228  $fsFiles = array();
229  foreach ( $sPaths as $i => $sPath ) {
230  $dPath = $dPaths[$i]; // destination
231  $sExists = $src->fileExists( array( 'src' => $sPath, 'latest' => 1 ) );
232  if ( $sExists === true ) { // exists in source
233  if ( $this->filesAreSame( $src, $dst, $sPath, $dPath ) ) {
234  continue; // avoid local copies for non-FS backends
235  }
236  // Note: getLocalReference() is fast for FS backends
237  $fsFile = $src->getLocalReference( array( 'src' => $sPath, 'latest' => 1 ) );
238  if ( !$fsFile ) {
239  $this->error( "Unable to sync '$dPath': could not get local copy." );
240  $status->fatal( 'backend-fail-internal', $src->getName() );
241  return $status;
242  }
243  $fsFiles[] = $fsFile; // keep TempFSFile objects alive as needed
244  // Note: prepare() is usually fast for key/value backends
245  $status->merge( $dst->prepare( array(
246  'dir' => dirname( $dPath ), 'bypassReadOnly' => 1 ) ) );
247  if ( !$status->isOK() ) {
248  return $status;
249  }
250  $ops[] = array( 'op' => 'store',
251  'src' => $fsFile->getPath(), 'dst' => $dPath, 'overwrite' => 1 );
252  } elseif ( $sExists === false ) { // does not exist in source
253  $ops[] = array( 'op' => 'delete', 'src' => $dPath, 'ignoreMissingSource' => 1 );
254  } else { // error
255  $this->error( "Unable to sync '$dPath': could not stat file." );
256  $status->fatal( 'backend-fail-internal', $src->getName() );
257  return $status;
258  }
259  }
260 
261  $t_start = microtime( true );
262  $status = $dst->doQuickOperations( $ops, array( 'bypassReadOnly' => 1 ) );
263  if ( !$status->isOK() ) {
264  sleep( 10 ); // wait and retry copy again
265  $status = $dst->doQuickOperations( $ops, array( 'bypassReadOnly' => 1 ) );
266  }
267  $ellapsed_ms = floor( ( microtime( true ) - $t_start ) * 1000 );
268  if ( $status->isOK() && $this->getOption( 'verbose' ) ) {
269  $this->output( "Synchronized these file(s) [{$ellapsed_ms}ms]:\n" .
270  implode( "\n", $dPaths ) . "\n" );
271  }
272 
273  return $status;
274  }
275 
282  protected function replaceNamePaths( $paths, FileBackend $backend ) {
283  return preg_replace(
284  '!^mwstore://([^/]+)!',
285  StringUtils::escapeRegexReplacement( "mwstore://" . $backend->getName() ),
286  $paths // string or array
287  );
288  }
289 
290  protected function filesAreSame( FileBackend $src, FileBackend $dst, $sPath, $dPath ) {
291  return (
292  ( $src->getFileSize( array( 'src' => $sPath ) )
293  === $dst->getFileSize( array( 'src' => $dPath ) ) // short-circuit
294  ) && ( $src->getFileSha1Base36( array( 'src' => $sPath ) )
295  === $dst->getFileSha1Base36( array( 'src' => $dPath ) )
296  )
297  );
298  }
299 }
300 
301 $maintClass = "SyncFileBackend";
302 require_once RUN_MAINTENANCE_IF_MAIN;
php
skin txt MediaWiki includes four core it has been set as the default in MediaWiki since the replacing Monobook it had been been the default skin since before being replaced by Vector largely rewritten in while keeping its appearance Several legacy skins were removed in the as the burden of supporting them became too heavy to bear Those in etc for skin dependent CSS etc for skin dependent JavaScript These can also be customised on a per user by etc This feature has led to a wide variety of user styles becoming that gallery is a good place to ending in php
Definition: skin.txt:62
FileBackend\preloadFileStat
preloadFileStat(array $params)
Preload file stat information (concurrently if possible) into in-process cache.
Definition: FileBackend.php:1215
$maintClass
$maintClass
Definition: syncFileBackend.php:301
FileBackend
Base class for all file backend classes (including multi-write backends).
Definition: FileBackend.php:85
LockManager\LOCK_UW
const LOCK_UW
Definition: LockManager.php:59
FileBackend\getName
getName()
Get the unique backend name.
Definition: FileBackend.php:167
SyncFileBackend\execute
execute()
Do the actual work.
Definition: syncFileBackend.php:48
Maintenance\addOption
addOption( $name, $description, $required=false, $withArg=false, $shortName=false)
Add a parameter to the script.
Definition: Maintenance.php:169
$time
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition: hooks.txt:1358
StringUtils\escapeRegexReplacement
static escapeRegexReplacement( $string)
Escape a string to make it suitable for inclusion in a preg_replace() replacement parameter.
Definition: StringUtils.php:296
Status\newGood
static newGood( $value=null)
Factory function for good results.
Definition: Status.php:77
RUN_MAINTENANCE_IF_MAIN
require_once RUN_MAINTENANCE_IF_MAIN
Definition: maintenance.txt:50
$limit
if( $sleep) $limit
Definition: importImages.php:99
Maintenance
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: maintenance.txt:39
SyncFileBackend
Maintenance script that syncs one file backend to another based on the journal of later.
Definition: syncFileBackend.php:32
true
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:1530
FileBackendGroup\singleton
static singleton()
Definition: FileBackendGroup.php:43
FileBackend\getScopedFileLocks
getScopedFileLocks(array $paths, $type, Status $status)
Lock the files at the given storage paths in the backend.
Definition: FileBackend.php:1262
FileBackend\getFileSize
getFileSize(array $params)
Get the size (bytes) of a file at a storage path in the backend.
SyncFileBackend\replaceNamePaths
replaceNamePaths( $paths, FileBackend $backend)
Substitute the backend name of storage paths with that of a given one.
Definition: syncFileBackend.php:282
FileBackend\getFileSha1Base36
getFileSha1Base36(array $params)
Get a SHA-1 hash of the file at a storage path in the backend.
SyncFileBackend\filesAreSame
filesAreSame(FileBackend $src, FileBackend $dst, $sPath, $dPath)
Definition: syncFileBackend.php:290
array
the array() calling protocol came about after MediaWiki 1.4rc1.
List of Api Query prop modules.
SyncFileBackend\syncFileBatch
syncFileBatch(array $paths, FileBackend $src, FileBackend $dst)
Sync particular files of backend $src to the corresponding $dst backend files.
Definition: syncFileBackend.php:206
wfWikiID
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
Definition: GlobalFunctions.php:3660
SyncFileBackend\__construct
__construct()
Default constructor.
Definition: syncFileBackend.php:33
Maintenance\isQuiet
isQuiet()
Definition: Maintenance.php:303
FileBackend\fileExists
fileExists(array $params)
Check if a file exists at a storage path in the backend.
FileBackend\doQuickOperations
doQuickOperations(array $ops, array $opts=array())
Perform a set of independent file operations on some files.
Definition: FileBackend.php:601
FileBackend\prepare
prepare(array $params)
Prepare a storage directory for usage.
Definition: FileBackend.php:754
SyncFileBackend\syncBackends
syncBackends(FileBackend $src, FileBackend $dst, $start, $end, Closure $callback)
Sync $dst backend to $src backend based on the $src logs given after $start.
Definition: syncFileBackend.php:151
Maintenance\getOption
getOption( $name, $default=null)
Get an option, or return the default.
Definition: Maintenance.php:191
as
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
Maintenance\error
error( $err, $die=0)
Throw an error to the user.
Definition: Maintenance.php:333
Maintenance\output
output( $out, $channel=null)
Throw some output to the user.
Definition: Maintenance.php:314
FileBackend\getJournal
getJournal()
Get the file journal object for this backend.
Definition: FileBackend.php:1319
FileBackend\getLocalReference
getLocalReference(array $params)
Returns a file system file, identical to the file at a storage path.
Definition: FileBackend.php:1021
Maintenance\hasOption
hasOption( $name)
Checks to see if a particular param exists.
Definition: Maintenance.php:181
LockManager\LOCK_EX
const LOCK_EX
Definition: LockManager.php:60
Maintenance\setBatchSize
setBatchSize( $s=0)
Set the batch size.
Definition: Maintenance.php:254