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