Fix bug in r83814 reported on IRC: categorymembers did not set an ORDER BY when cmcon...
[mediawiki.git] / maintenance / storage / trackBlobs.php
blobb5f800479a02dc93b9ada9a02f7a8ee65a24278d
1 <?php
2 /**
3 * Adds blobs from a given external storage cluster to the blob_tracking table.
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
20 * @file
21 * @ingroup Maintenance
22 * @see wfWaitForSlaves()
25 require( dirname( __FILE__ ) . '/../commandLine.inc' );
28 if ( count( $args ) < 1 ) {
29 echo "Usage: php trackBlobs.php <cluster> [... <cluster>]\n";
30 echo "Adds blobs from a given ES cluster to the blob_tracking table\n";
31 echo "Automatically deletes the tracking table and starts from the start again when restarted.\n";
33 exit( 1 );
35 $tracker = new TrackBlobs( $args );
36 $tracker->run();
37 echo "All done.\n";
39 class TrackBlobs {
40 var $clusters, $textClause;
41 var $doBlobOrphans;
42 var $trackedBlobs = array();
44 var $batchSize = 1000;
45 var $reportingInterval = 10;
47 function __construct( $clusters ) {
48 $this->clusters = $clusters;
49 if ( extension_loaded( 'gmp' ) ) {
50 $this->doBlobOrphans = true;
51 foreach ( $clusters as $cluster ) {
52 $this->trackedBlobs[$cluster] = gmp_init( 0 );
54 } else {
55 echo "Warning: the gmp extension is needed to find orphan blobs\n";
59 function run() {
60 $this->checkIntegrity();
61 $this->initTrackingTable();
62 $this->trackRevisions();
63 $this->trackOrphanText();
64 if ( $this->doBlobOrphans ) {
65 $this->findOrphanBlobs();
69 function checkIntegrity() {
70 echo "Doing integrity check...\n";
71 $dbr = wfGetDB( DB_SLAVE );
73 // Scan for HistoryBlobStub objects in the text table (bug 20757)
75 $exists = $dbr->selectField( 'text', 1,
76 'old_flags LIKE \'%object%\' AND old_flags NOT LIKE \'%external%\' ' .
77 'AND LOWER(CONVERT(LEFT(old_text,22) USING latin1)) = \'o:15:"historyblobstub"\'',
78 __METHOD__
81 if ( $exists ) {
82 echo "Integrity check failed: found HistoryBlobStub objects in your text table.\n" .
83 "This script could destroy these objects if it continued. Run resolveStubs.php\n" .
84 "to fix this.\n";
85 exit( 1 );
88 // Scan the archive table for HistoryBlobStub objects or external flags (bug 22624)
89 $flags = $dbr->selectField( 'archive', 'ar_flags',
90 'ar_flags LIKE \'%external%\' OR (' .
91 'ar_flags LIKE \'%object%\' ' .
92 'AND LOWER(CONVERT(LEFT(ar_text,22) USING latin1)) = \'o:15:"historyblobstub"\' )',
93 __METHOD__
96 if ( strpos( $flags, 'external' ) !== false ) {
97 echo "Integrity check failed: found external storage pointers in your archive table.\n" .
98 "Run normaliseArchiveTable.php to fix this.\n";
99 exit( 1 );
100 } elseif ( $flags ) {
101 echo "Integrity check failed: found HistoryBlobStub objects in your archive table.\n" .
102 "These objects are probably already broken, continuing would make them\n" .
103 "unrecoverable. Run \"normaliseArchiveTable.php --fix-cgz-bug\" to fix this.\n";
104 exit( 1 );
107 echo "Integrity check OK\n";
110 function initTrackingTable() {
111 $dbw = wfGetDB( DB_MASTER );
112 if ( $dbw->tableExists( 'blob_tracking' ) ) {
113 $dbw->query( 'DROP TABLE ' . $dbw->tableName( 'blob_tracking' ) );
114 $dbw->query( 'DROP TABLE ' . $dbw->tableName( 'blob_orphans' ) );
116 $dbw->sourceFile( dirname( __FILE__ ) . '/blob_tracking.sql' );
119 function getTextClause() {
120 if ( !$this->textClause ) {
121 $dbr = wfGetDB( DB_SLAVE );
122 $this->textClause = '';
123 foreach ( $this->clusters as $cluster ) {
124 if ( $this->textClause != '' ) {
125 $this->textClause .= ' OR ';
127 $this->textClause .= 'old_text' . $dbr->buildLike( "DB://$cluster/", $dbr->anyString() );
130 return $this->textClause;
133 function interpretPointer( $text ) {
134 if ( !preg_match( '!^DB://(\w+)/(\d+)(?:/([0-9a-fA-F]+)|)$!', $text, $m ) ) {
135 return false;
137 return array(
138 'cluster' => $m[1],
139 'id' => intval( $m[2] ),
140 'hash' => isset( $m[3] ) ? $m[3] : null
145 * Scan the revision table for rows stored in the specified clusters
147 function trackRevisions() {
148 $dbw = wfGetDB( DB_MASTER );
149 $dbr = wfGetDB( DB_SLAVE );
151 $textClause = $this->getTextClause();
152 $startId = 0;
153 $endId = $dbr->selectField( 'revision', 'MAX(rev_id)', false, __METHOD__ );
154 $batchesDone = 0;
155 $rowsInserted = 0;
157 echo "Finding revisions...\n";
159 while ( true ) {
160 $res = $dbr->select( array( 'revision', 'text' ),
161 array( 'rev_id', 'rev_page', 'old_id', 'old_flags', 'old_text' ),
162 array(
163 'rev_id > ' . $dbr->addQuotes( $startId ),
164 'rev_text_id=old_id',
165 $textClause,
166 'old_flags ' . $dbr->buildLike( $dbr->anyString(), 'external', $dbr->anyString() ),
168 __METHOD__,
169 array(
170 'ORDER BY' => 'rev_id',
171 'LIMIT' => $this->batchSize
174 if ( !$res->numRows() ) {
175 break;
178 $insertBatch = array();
179 foreach ( $res as $row ) {
180 $startId = $row->rev_id;
181 $info = $this->interpretPointer( $row->old_text );
182 if ( !$info ) {
183 echo "Invalid DB:// URL in rev_id {$row->rev_id}\n";
184 continue;
186 if ( !in_array( $info['cluster'], $this->clusters ) ) {
187 echo "Invalid cluster returned in SQL query: {$info['cluster']}\n";
188 continue;
190 $insertBatch[] = array(
191 'bt_page' => $row->rev_page,
192 'bt_rev_id' => $row->rev_id,
193 'bt_text_id' => $row->old_id,
194 'bt_cluster' => $info['cluster'],
195 'bt_blob_id' => $info['id'],
196 'bt_cgz_hash' => $info['hash']
198 if ( $this->doBlobOrphans ) {
199 gmp_setbit( $this->trackedBlobs[$info['cluster']], $info['id'] );
202 $dbw->insert( 'blob_tracking', $insertBatch, __METHOD__ );
203 $rowsInserted += count( $insertBatch );
205 ++$batchesDone;
206 if ( $batchesDone >= $this->reportingInterval ) {
207 $batchesDone = 0;
208 echo "$startId / $endId\n";
209 wfWaitForSlaves();
212 echo "Found $rowsInserted revisions\n";
216 * Scan the text table for orphan text
217 * Orphan text here does not imply DB corruption -- deleted text tracked by the
218 * archive table counts as orphan for our purposes.
220 function trackOrphanText() {
221 # Wait until the blob_tracking table is available in the slave
222 $dbw = wfGetDB( DB_MASTER );
223 $dbr = wfGetDB( DB_SLAVE );
224 $pos = $dbw->getMasterPos();
225 $dbr->masterPosWait( $pos, 100000 );
227 $textClause = $this->getTextClause( $this->clusters );
228 $startId = 0;
229 $endId = $dbr->selectField( 'text', 'MAX(old_id)', false, __METHOD__ );
230 $rowsInserted = 0;
231 $batchesDone = 0;
233 echo "Finding orphan text...\n";
235 # Scan the text table for orphan text
236 while ( true ) {
237 $res = $dbr->select( array( 'text', 'blob_tracking' ),
238 array( 'old_id', 'old_flags', 'old_text' ),
239 array(
240 'old_id>' . $dbr->addQuotes( $startId ),
241 $textClause,
242 'old_flags ' . $dbr->buildLike( $dbr->anyString(), 'external', $dbr->anyString() ),
243 'bt_text_id IS NULL'
245 __METHOD__,
246 array(
247 'ORDER BY' => 'old_id',
248 'LIMIT' => $this->batchSize
250 array( 'blob_tracking' => array( 'LEFT JOIN', 'bt_text_id=old_id' ) )
252 $ids = array();
253 foreach ( $res as $row ) {
254 $ids[] = $row->old_id;
257 if ( !$res->numRows() ) {
258 break;
261 $insertBatch = array();
262 foreach ( $res as $row ) {
263 $startId = $row->old_id;
264 $info = $this->interpretPointer( $row->old_text );
265 if ( !$info ) {
266 echo "Invalid DB:// URL in old_id {$row->old_id}\n";
267 continue;
269 if ( !in_array( $info['cluster'], $this->clusters ) ) {
270 echo "Invalid cluster returned in SQL query\n";
271 continue;
274 $insertBatch[] = array(
275 'bt_page' => 0,
276 'bt_rev_id' => 0,
277 'bt_text_id' => $row->old_id,
278 'bt_cluster' => $info['cluster'],
279 'bt_blob_id' => $info['id'],
280 'bt_cgz_hash' => $info['hash']
282 if ( $this->doBlobOrphans ) {
283 gmp_setbit( $this->trackedBlobs[$info['cluster']], $info['id'] );
286 $dbw->insert( 'blob_tracking', $insertBatch, __METHOD__ );
288 $rowsInserted += count( $insertBatch );
289 ++$batchesDone;
290 if ( $batchesDone >= $this->reportingInterval ) {
291 $batchesDone = 0;
292 echo "$startId / $endId\n";
293 wfWaitForSlaves();
296 echo "Found $rowsInserted orphan text rows\n";
300 * Scan the blobs table for rows not registered in blob_tracking (and thus not
301 * registered in the text table).
303 * Orphan blobs are indicative of DB corruption. They are inaccessible and
304 * should probably be deleted.
306 function findOrphanBlobs() {
307 if ( !extension_loaded( 'gmp' ) ) {
308 echo "Can't find orphan blobs, need bitfield support provided by GMP.\n";
309 return;
312 $dbw = wfGetDB( DB_MASTER );
314 foreach ( $this->clusters as $cluster ) {
315 echo "Searching for orphan blobs in $cluster...\n";
316 $lb = wfGetLBFactory()->getExternalLB( $cluster );
317 try {
318 $extDB = $lb->getConnection( DB_SLAVE );
319 } catch ( DBConnectionError $e ) {
320 if ( strpos( $e->error, 'Unknown database' ) !== false ) {
321 echo "No database on $cluster\n";
322 } else {
323 echo "Error on $cluster: " . $e->getMessage() . "\n";
325 continue;
327 $table = $extDB->getLBInfo( 'blobs table' );
328 if ( is_null( $table ) ) {
329 $table = 'blobs';
331 if ( !$extDB->tableExists( $table ) ) {
332 echo "No blobs table on cluster $cluster\n";
333 continue;
335 $startId = 0;
336 $batchesDone = 0;
337 $actualBlobs = gmp_init( 0 );
338 $endId = $extDB->selectField( $table, 'MAX(blob_id)', false, __METHOD__ );
340 // Build a bitmap of actual blob rows
341 while ( true ) {
342 $res = $extDB->select( $table,
343 array( 'blob_id' ),
344 array( 'blob_id > ' . $extDB->addQuotes( $startId ) ),
345 __METHOD__,
346 array( 'LIMIT' => $this->batchSize, 'ORDER BY' => 'blob_id' )
349 if ( !$res->numRows() ) {
350 break;
353 foreach ( $res as $row ) {
354 gmp_setbit( $actualBlobs, $row->blob_id );
356 $startId = $row->blob_id;
358 ++$batchesDone;
359 if ( $batchesDone >= $this->reportingInterval ) {
360 $batchesDone = 0;
361 echo "$startId / $endId\n";
365 // Find actual blobs that weren't tracked by the previous passes
366 // This is a set-theoretic difference A \ B, or in bitwise terms, A & ~B
367 $orphans = gmp_and( $actualBlobs, gmp_com( $this->trackedBlobs[$cluster] ) );
369 // Traverse the orphan list
370 $insertBatch = array();
371 $id = 0;
372 $numOrphans = 0;
373 while ( true ) {
374 $id = gmp_scan1( $orphans, $id );
375 if ( $id == -1 ) {
376 break;
378 $insertBatch[] = array(
379 'bo_cluster' => $cluster,
380 'bo_blob_id' => $id
382 if ( count( $insertBatch ) > $this->batchSize ) {
383 $dbw->insert( 'blob_orphans', $insertBatch, __METHOD__ );
384 $insertBatch = array();
387 ++$id;
388 ++$numOrphans;
390 if ( $insertBatch ) {
391 $dbw->insert( 'blob_orphans', $insertBatch, __METHOD__ );
393 echo "Found $numOrphans orphan(s) in $cluster\n";