44 private $revisionStore;
54 private $loadBalancer;
62 parent::__construct();
65 $this->
addDescription(
'Find and mark bad content blobs. Marked blobs will be read as empty. '
66 .
'Use --scan-from to find revisions with bad blobs, use --mark to mark them.' );
67 $this->
addOption(
'scan-from',
'Start scanning revisions at the given date. '
68 .
'Format: Anything supported by MediaWiki, e.g. YYYYMMDDHHMMSS or YYYY-MM-DDTHH:MM:SS',
70 $this->
addOption(
'revisions',
'A list of revision IDs to process, separated by comma or '
71 .
'colon or whitespace. Revisions belonging to deleted pages will work. '
72 .
'If set to "-" IDs are read from stdin, one per line.',
false,
true );
73 $this->
addOption(
'limit',
'Maximum number of revisions for --scan-from to scan. '
74 .
'Default: 1000',
false,
true );
75 $this->
addOption(
'mark',
'Mark the blob as "known bad", to avoid errors when '
76 .
'attempting to read it. The value given is the reason for marking the blob as bad, '
77 .
'typically a ticket ID. Requires --revisions to also be set.',
false,
true );
86 $services = MediaWikiServices::getInstance();
88 $this->revisionStore = $revisionStore ?? $this->revisionStore ?? $services->getRevisionStore();
89 $this->blobStore = $blobStore ?? $this->blobStore ?? $services->getBlobStore();
90 $this->loadBalancer = $loadBalancer ?? $this->loadBalancer ?? $services->getDBLoadBalancer();
91 $this->lbFactory = $lbFactory ?? $this->lbFactory ?? $services->getDBLoadBalancerFactory();
97 private function getStartTimestamp() {
99 if ( strlen( $tsOpt ) < 14 ) {
101 .
', please provide time and date down to the second.' );
106 $this->
fatalError(
'Bad timestamp: ' . $tsOpt );
115 private function getRevisionIds() {
118 if ( $opt ===
'-' ) {
119 $opt = stream_get_contents( STDIN );
137 $this->
fatalError(
'Cannot use --revisions together with --scan-from' );
140 $ids = $this->getRevisionIds();
142 $count = $this->scanRevisionsById( $ids );
143 } elseif ( $this->
hasOption(
'scan-from' ) ) {
145 $this->
fatalError(
'Cannot use --mark with --scan-from, '
146 .
'use --revisions to specify revisions to mark.' );
149 $fromTimestamp = $this->getStartTimestamp();
150 $total = $this->
getOption(
'limit', 1000 );
152 $count = $this->scanRevisionsByTimestamp( $fromTimestamp, $total );
154 $this->
output(
"The range of archive rows scanned is based on the range of revision IDs "
155 .
"scanned in the revision table.\n" );
158 $this->
fatalError(
'The --mark must be used together with --revisions' );
160 $this->
fatalError(
'Must specify one of --revisions or --scan-from' );
165 $this->
output(
"Marked $count bad revisions.\n" );
167 $this->
output(
"Found $count bad revisions.\n" );
170 $this->
output(
"On a unix/linux environment, you can use grep and cut to list of IDs\n" );
171 $this->
output(
"that can then be used with the --revisions option. E.g.\n" );
172 $this->
output(
" grep '! Found bad blob' | cut -s -f 3\n" );
183 private function scanRevisionsByTimestamp( $fromTimestamp, $total ) {
187 $lastTimestamp = $fromTimestamp;
188 $revisionRowsScanned = 0;
189 $archiveRowsScanned = 0;
191 $this->
output(
"Scanning revisions table, "
192 .
"$total rows starting at rev_timestamp $fromTimestamp\n" );
194 while ( $revisionRowsScanned < $total ) {
195 $batchSize = min( $total - $revisionRowsScanned, $this->
getBatchSize() );
196 $revisions = $this->loadRevisionsByTimestamp( $lastRevId, $lastTimestamp, $batchSize );
201 foreach ( $revisions as $rev ) {
203 $firstRevId = $firstRevId ? min( $firstRevId, $rev->getId() ) : $rev->getId();
204 $lastRevId = max( $lastRevId, $rev->getId() );
206 $count += $this->checkRevision( $rev );
209 $lastTimestamp = $rev->getTimestamp();
210 $batchSize = count( $revisions );
211 $revisionRowsScanned += $batchSize;
213 "\t- Scanned a batch of $batchSize revisions, "
214 .
"up to revision $lastRevId ($lastTimestamp)\n"
225 $fromArchived = $this->getNextRevision( $firstRevId,
'<',
'DESC' );
226 $maxArchived = $this->getNextRevision( $lastRevId,
'>',
'ASC' );
227 $maxArchived = $maxArchived ?: PHP_INT_MAX;
229 $this->
output(
"Scanning archive table by ar_rev_id, $fromArchived to $maxArchived\n" );
230 while ( $firstRevId > 0 && $fromArchived < $maxArchived ) {
231 $batchSize = min( $total - $archiveRowsScanned, $this->
getBatchSize() );
232 $revisions = $this->loadArchiveByRevisionId( $fromArchived, $maxArchived, $batchSize );
237 foreach ( $revisions as $rev ) {
238 $count += $this->checkRevision( $rev );
240 $fromArchived = $rev->getId();
241 $batchSize = count( $revisions );
242 $archiveRowsScanned += $batchSize;
244 "\t- Scanned a batch of $batchSize archived revisions, "
245 .
"up to revision $fromArchived ($lastTimestamp)\n"
261 private function loadRevisionsByTimestamp(
int $afterId,
string $fromTimestamp, $batchSize ) {
262 $db = $this->loadBalancer->getConnectionRef(
DB_REPLICA );
263 $queryInfo = $this->revisionStore->getQueryInfo();
264 $rows = $db->newSelectQueryBuilder()
265 ->select( $queryInfo[
'fields'] )
266 ->tables( $queryInfo[
'tables'] )
267 ->where( $db->buildComparison(
'>', [
268 'rev_timestamp' => $fromTimestamp,
269 'rev_id' => $afterId,
271 ->joinConds( $queryInfo[
'joins'] )
272 ->useIndex( [
'revision' =>
'rev_timestamp' ] )
273 ->orderBy( [
'rev_timestamp',
'rev_id' ] )
274 ->limit( $batchSize )
275 ->caller( __METHOD__ )
277 $result = $this->revisionStore->newRevisionsFromBatch( $rows, [
'slots' =>
true ] );
278 $this->handleStatus( $result );
280 $records = array_filter( $result->value );
282 '@phan-var RevisionStoreRecord[] $records';
293 private function loadArchiveByRevisionId(
int $afterId,
int $uptoId, $batchSize ) {
294 $db = $this->loadBalancer->getConnectionRef(
DB_REPLICA );
295 $queryInfo = $this->revisionStore->getArchiveQueryInfo();
296 $rows = $db->newSelectQueryBuilder()
297 ->select( $queryInfo[
'fields'] )
298 ->tables( $queryInfo[
'tables'] )
299 ->where( [
"ar_rev_id > $afterId",
"ar_rev_id <= $uptoId" ] )
300 ->joinConds( $queryInfo[
'joins'] )
301 ->orderBy(
'ar_rev_id' )
302 ->limit( $batchSize )
303 ->caller( __METHOD__ )
305 $result = $this->revisionStore->newRevisionsFromBatch(
307 [
'archive' =>
true,
'slots' =>
true ]
309 $this->handleStatus( $result );
311 $records = array_filter( $result->value );
313 '@phan-var RevisionArchiveRecord[] $records';
326 private function getNextRevision(
int $revId,
string $comp,
string $dir ) {
327 $db = $this->loadBalancer->getConnectionRef(
DB_REPLICA );
328 $next = $db->newSelectQueryBuilder()
331 ->where(
"rev_id $comp $revId" )
332 ->orderBy( [
"rev_id" ], $dir )
333 ->caller( __METHOD__ )
343 private function scanRevisionsById( array $ids ) {
345 $total = count( $ids );
347 $this->
output(
"Scanning $total ids\n" );
349 foreach ( array_chunk( $ids, $this->
getBatchSize() ) as $batch ) {
350 $revisions = $this->loadRevisionsById( $batch );
357 foreach ( $revisions as $rev ) {
358 $count += $this->checkRevision( $rev );
361 $batchSize = count( $revisions );
362 $this->
output(
"\t- Scanned a batch of $batchSize revisions\n" );
373 private function loadRevisionsById( array $ids ) {
374 $db = $this->loadBalancer->getConnectionRef(
DB_REPLICA );
375 $queryInfo = $this->revisionStore->getQueryInfo();
377 $rows = $db->newSelectQueryBuilder()
378 ->select( $queryInfo[
'fields'] )
379 ->tables( $queryInfo[
'tables'] )
380 ->where( [
'rev_id' => $ids ] )
381 ->joinConds( $queryInfo[
'joins'] )
382 ->caller( __METHOD__ )
385 $result = $this->revisionStore->newRevisionsFromBatch( $rows, [
'slots' =>
true ] );
387 $this->handleStatus( $result );
389 $revisions = array_filter( $result->value );
390 '@phan-var RevisionArchiveRecord[] $revisions';
393 if ( count( $revisions ) < count( $ids ) ) {
394 $archiveQueryInfo = $this->revisionStore->getArchiveQueryInfo();
395 $remainingIds = array_diff( $ids, array_keys( $revisions ) );
397 $rows = $db->newSelectQueryBuilder()
398 ->select( $archiveQueryInfo[
'fields'] )
399 ->tables( $archiveQueryInfo[
'tables'] )
400 ->where( [
'ar_rev_id' => $remainingIds ] )
401 ->joinConds( $archiveQueryInfo[
'joins'] )
402 ->caller( __METHOD__ )
405 $archiveResult = $this->revisionStore->newRevisionsFromBatch(
407 [
'slots' =>
true,
'archive' =>
true ]
410 $this->handleStatus( $archiveResult );
413 $revisions += array_filter( $archiveResult->value );
426 foreach ( $rev->
getSlots()->getSlots() as $slot ) {
427 $count += $this->checkSlot( $rev, $slot );
430 if ( $count === 0 && $this->
hasOption(
'mark' ) ) {
431 $this->
output(
"\t# No bad blob found on revision {$rev->getId()}, skipped!\n" );
447 $this->blobStore->getBlob( $address );
450 }
catch ( Exception $ex ) {
451 $error = $ex->getMessage();
452 $type = get_class( $ex );
457 $this->
output(
"\t! Found bad blob on revision {$rev->getId()} "
458 .
"from {$rev->getTimestamp()} ({$slot->getRole()} slot): "
459 .
"content_id={$slot->getContentId()}, address=<{$slot->getAddress()}>, "
460 .
"error='$error', type='$type'. ID:\t{$rev->getId()}\n" );
463 $newAddress = $this->markBlob( $slot, $error );
464 $this->
output(
"\tChanged address to <$newAddress>\n" );
476 private function markBlob(
SlotRecord $slot,
string $error =
null ) {
480 $args[
'reason'] = $this->
getOption(
'mark' );
484 $args[
'error'] = $error;
488 $badAddress =
'bad:' . urlencode( $address );
494 $badAddress = substr( $badAddress, 0, 255 );
496 $dbw = $this->loadBalancer->getConnectionRef(
DB_PRIMARY );
499 [
'content_address' => $badAddress ],
507 private function handleStatus(
StatusValue $status ) {
508 if ( !$status->
isOK() ) {
510 Status::wrap( $status )->getMessage(
false,
false,
'en' )->text()
513 if ( !$status->
isGood() ) {
515 "\t! " . Status::wrap( $status )->getMessage(
false,
false,
'en' )->text()
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
error( $err, $die=0)
Throw an error to the user.
output( $out, $channel=null)
Throw some output to the user.
hasOption( $name)
Checks to see if a particular option was set.
parseIntList( $text)
Utility function to parse a string (perhaps from a command line option) into a list of integers (perh...
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
getOption( $name, $default=null)
Get an option, or return the default.
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.