Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
179 / 179
100.00% covered (success)
100.00%
8 / 8
CRAP
100.00% covered (success)
100.00%
1 / 1
ScanFilesInScanTable
100.00% covered (success)
100.00%
179 / 179
100.00% covered (success)
100.00%
8 / 8
33
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
60 / 60
100.00% covered (success)
100.00%
1 / 1
1
 execute
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
4
 maybeOutputVerboseScanResult
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
8
 initServices
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 parseLastCheckedTimestamp
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
7
 generateSha1ValuesForScan
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
2
 waitForJobQueueSize
100.00% covered (success)
100.00%
32 / 32
100.00% covered (success)
100.00%
1 / 1
7
 pollSha1ValuesForScanCompletion
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2declare( strict_types=1 );
3
4namespace MediaWiki\Extension\MediaModeration\Maintenance;
5
6use MediaWiki\Context\RequestContext;
7use MediaWiki\Extension\MediaModeration\Services\MediaModerationDatabaseLookup;
8use MediaWiki\Extension\MediaModeration\Services\MediaModerationFileScanner;
9use MediaWiki\JobQueue\Exceptions\JobQueueError;
10use MediaWiki\JobQueue\JobQueueGroup;
11use MediaWiki\JobQueue\JobSpecification;
12use MediaWiki\Maintenance\Maintenance;
13use MediaWiki\Status\StatusFormatter;
14use StatusValue;
15use Wikimedia\Rdbms\IDBAccessObject;
16use Wikimedia\Rdbms\SelectQueryBuilder;
17use Wikimedia\Timestamp\ConvertibleTimestamp;
18
19// @codeCoverageIgnoreStart
20$IP = getenv( 'MW_INSTALL_PATH' );
21if ( $IP === false ) {
22    $IP = __DIR__ . '/../../..';
23}
24require_once "$IP/maintenance/Maintenance.php";
25// @codeCoverageIgnoreEnd
26
27/**
28 * Scans files referenced by their SHA-1 value in the mediamoderation_scan table.
29 */
30class ScanFilesInScanTable extends Maintenance {
31
32    private MediaModerationDatabaseLookup $mediaModerationDatabaseLookup;
33    private MediaModerationFileScanner $mediaModerationFileScanner;
34    private JobQueueGroup $jobQueueGroup;
35    private StatusFormatter $statusFormatter;
36
37    private ?string $lastChecked;
38    /** @var array If --use-jobqueue is specified, holds the SHA-1 values currently being processed by the job queue. */
39    private array $sha1ValuesBeingProcessed = [];
40
41    public function __construct() {
42        parent::__construct();
43
44        $this->requireExtension( 'MediaModeration' );
45        $this->addDescription( 'Maintenance script to scan files listed in the mediamoderation_scan table.' );
46
47        $this->addOption(
48            'last-checked',
49            'Only scan files (referenced by their SHA-1 value internally) where the last attempted scan ' .
50            'was before this date (including never checked files). The default is to filter for files last attempted ' .
51            "to be scanned before today. To only scan files that have never been scanned before specify 'never'. The " .
52            'accepted format is YYYYMMDD or a timestamp supported by ConvertibleTimestamp. Files that have been ' .
53            'successfully scanned (i.e. the match status is not null) are not re-scanned by this script.',
54        );
55        $this->addOption(
56            'use-jobqueue',
57            'Scan files concurrently using the job queue. Each job scans one SHA-1 and are added in ' .
58            'batches of --batch-size. The script waits to add more jobs until the number of jobs left processing ' .
59            'less than --poll-until. Using the job queue increases the speed of scanning, but disables output to ' .
60            'console about the status of scans as these are handled by jobs which produce no console output.',
61        );
62        $this->addOption(
63            'sleep',
64            'Sleep time (in seconds) between every batch of SHA-1 values scanned. Default: 1',
65            false,
66            true
67        );
68        $this->addOption(
69            'poll-sleep',
70            'Sleep time (in seconds) between every poll to check for completed scanning jobs. This is done ' .
71            'so that the script does not add more jobs to scan SHA-1 values until the SHA-1 values being currently ' .
72            'processed is equal or less than --poll-until. Does nothing if the --use-jobqueue option is not ' .
73            'specified. Default: 1',
74            false,
75            true
76        );
77        $this->addOption(
78            'poll-until',
79            'If --use-jobqueue is specified, used to wait until there are this or less SHA-1s being ' .
80            'currently being processed by the job queue. This is checked via polling and the speed of polling is ' .
81            'controlled by --poll-sleep. The default for this option is half of the value of --batch-size (which ' .
82            'is 200 by default).',
83            false,
84            true
85        );
86        $this->addOption(
87            'max-polls',
88            'If --use-jobqueue is specified, then this controls the number of times that the status of ' .
89            'scans in the job queue are polled. If the number of times polled exceeds this value the array that ' .
90            'tracks the SHA-1 values currently being processed is emptied to avoid failed jobs causing the script ' .
91            'to infinitely loop.',
92            false,
93            true
94        );
95        $this->addOption(
96            'verbose',
97            'Enables verbose mode which prints out information once a SHA-1 has finished being scanned.' .
98            'If --use-jobqueue is specified, this instead prints out information about the jobs being queued.',
99            false,
100            false,
101            'v'
102        );
103
104        $this->setBatchSize( 200 );
105    }
106
107    public function execute() {
108        $this->initServices();
109        $this->parseLastCheckedTimestamp();
110
111        foreach ( $this->generateSha1ValuesForScan() as $sha1 ) {
112            if ( $this->hasOption( 'use-jobqueue' ) ) {
113                // Push scan jobs to the job queue if --use-jobqueue is set.
114                // To monitor the status of scans when using the job queue it
115                // is intended that the user monitors statsd / the logging channel.
116                try {
117                    $this->jobQueueGroup->push( new JobSpecification(
118                        'mediaModerationScanFileJob',
119                        [ 'sha1' => $sha1 ]
120                    ) );
121                } catch ( JobQueueError ) {
122                    // If the job failed to be inserted, then catch the exception and sleep as this can occur if the
123                    // server is experiencing instability.
124                    sleep( intval( $this->getOption( 'sleep', 1 ) ) );
125                }
126            } else {
127                $scanStatus = $this->mediaModerationFileScanner->scanSha1( $sha1 );
128                $this->maybeOutputVerboseScanResult( $sha1, $scanStatus );
129            }
130        }
131    }
132
133    /**
134     * Outputs verbose information about the status of a scan for a provided SHA-1 if
135     * verbose mode is enabled via the --verbose command line argument.
136     *
137     * @param string $sha1 The SHA-1 that was just checked
138     * @param StatusValue $checkResult The StatusValue as returned by MediaModerationFileScanner::scanSha1
139     * @return void
140     */
141    protected function maybeOutputVerboseScanResult( string $sha1, StatusValue $checkResult ) {
142        if ( !$this->hasOption( 'verbose' ) ) {
143            return;
144        }
145        // Output any warnings or errors.
146        if ( !$checkResult->isGood() && count( $checkResult->getErrors() ) ) {
147            $this->error( "SHA-1 $sha1\n" );
148            if ( count( $checkResult->getErrors() ) === 1 ) {
149                $this->error( '* ' . $this->statusFormatter->getWikiText( $checkResult ) . "\n" );
150            } elseif ( count( $checkResult->getErrors() ) > 1 ) {
151                $this->error( $this->statusFormatter->getWikiText( $checkResult ) );
152            }
153        }
154        $outputString = "SHA-1 $sha1: ";
155        if ( $checkResult->getValue() === null ) {
156            $outputString .= "Scan failed.\n";
157            // If the scan failed, make this an error output.
158            $this->error( $outputString );
159            return;
160        }
161        if ( $checkResult->getValue() ) {
162            $outputString .= "Positive match.\n";
163        } else {
164            $outputString .= "No match.\n";
165        }
166        $this->output( $outputString );
167    }
168
169    protected function initServices() {
170        $services = $this->getServiceContainer();
171        $this->mediaModerationDatabaseLookup = $services->get( 'MediaModerationDatabaseLookup' );
172        $this->mediaModerationFileScanner = $services->get( 'MediaModerationFileScanner' );
173        $this->jobQueueGroup = $services->getJobQueueGroup();
174        $this->statusFormatter = $services->getFormatterFactory()->getStatusFormatter( RequestContext::getMain() );
175    }
176
177    /**
178     * Parse the 'last-checked' timestamp provided via the command line,
179     * and cause a fatal error if it cannot be parsed.
180     *
181     * @return void
182     */
183    protected function parseLastCheckedTimestamp() {
184        $lastChecked = $this->getOption(
185            'last-checked',
186            // Subtract one day from the current date for the default of 'last-checked'
187            ConvertibleTimestamp::time() - 60 * 60 * 24
188        );
189        // If the 'last-checked' option is the string "never", then convert this to null.
190        if ( $lastChecked === "never" ) {
191            $this->lastChecked = null;
192        } elseif ( strlen( (string)$lastChecked ) === 8 && (string)$lastChecked === strval( intval( $lastChecked ) ) ) {
193            // The 'last-checked' argument is likely to be in the form YYYYMMDD because:
194            // * The length of the argument is 8 (which is the length of a YYYYMMDD format)
195            // * The intval of the 'last-checked' parameter can be converted to an integer
196            //    and from a string without any changes in value (thus it must be an integer
197            //    in string form).
198            // Convert it to a TS_MW timestamp by adding 000000 to the end (the time component).
199            if (
200                $lastChecked === $this->mediaModerationDatabaseLookup
201                    ->getDateFromTimestamp( ConvertibleTimestamp::now() )
202            ) {
203                $this->fatalError( 'The --last-checked argument cannot be the current date.' );
204            }
205            $this->lastChecked = $lastChecked . '000000';
206        } elseif ( ConvertibleTimestamp::convert( TS_MW, $lastChecked ) ) {
207            // If the 'last-checked' argument is recognised as a timestamp by ConvertibleTimestamp::convert,
208            // then get the date part and discard the time part (replacing it with 000000).
209            $dateFromTimestamp = $this->mediaModerationDatabaseLookup->getDateFromTimestamp( $lastChecked );
210            if (
211                $dateFromTimestamp === $this->mediaModerationDatabaseLookup
212                    ->getDateFromTimestamp( ConvertibleTimestamp::now() )
213            ) {
214                $this->fatalError( 'The --last-checked argument cannot be the current date.' );
215            }
216            $this->lastChecked = $dateFromTimestamp . '000000';
217        } else {
218            // The 'last-checked' argument could not be parsed, so raise an error
219            $this->fatalError(
220                'The --last-checked argument passed to this script could not be parsed. This can take a ' .
221                'timestamp in string form, or a date in YYYYMMDD format.'
222            );
223        }
224    }
225
226    /**
227     * Generates SHA-1 values for to be scanned. This function pauses for the
228     * specified number of seconds after each batch of SHA-1 values.
229     *
230     * @return \Generator
231     */
232    protected function generateSha1ValuesForScan(): \Generator {
233        do {
234            $batch = $this->mediaModerationDatabaseLookup->getSha1ValuesForScan(
235                $this->getBatchSize() ?? 200,
236                $this->lastChecked,
237                SelectQueryBuilder::SORT_ASC,
238                $this->sha1ValuesBeingProcessed,
239                MediaModerationDatabaseLookup::NULL_MATCH_STATUS
240            );
241            // Store the number of rows returned to determine if another batch should be performed.
242            $lastBatchRowCount = count( $batch );
243            yield from $batch;
244            // Sleep for the number of seconds specified in the 'sleep' option.
245            sleep( intval( $this->getOption( 'sleep', 1 ) ) );
246            if ( $this->hasOption( 'use-jobqueue' ) ) {
247                // Wait until the number of SHA-1 values being processed drops below a specific count.
248                $this->waitForJobQueueSize( $batch );
249            }
250            // Wait for replication so that updates to the mms_is_match and mms_last_checked
251            // on the rows processed in this batch are replicated to replica DBs.
252            $this->waitForReplication();
253        } while ( $lastBatchRowCount !== 0 );
254    }
255
256    /**
257     * Waits for the number of SHA-1 values currently being processed using jobs to be less
258     * than half the batch size.
259     *
260     * When in verbose mode this method also prints out information about the SHA-1 values being processed.
261     *
262     * @param array $batch The new batch of SHA-1s being processed. If no batch was added,
263     *   specify an empty array.
264     * @return void
265     */
266    protected function waitForJobQueueSize( array $batch ) {
267        $pollUntil = intval( $this->getOption( 'poll-until', floor( ( $this->getBatchSize() ?? 200 ) / 2 ) ) );
268        if ( $this->hasOption( 'verbose' ) ) {
269            // If in verbose mode, print out the batch that was just added to the console.
270            $batchSize = count( $batch );
271            $this->output(
272                "Added $batchSize SHA-1 value(s) for scanning via the job queue: " .
273                implode( ', ', $batch ) . "\n"
274            );
275        }
276        // Add the new SHA-1 values being processed by the job queue to the array keeping track
277        // of the job queue count. Needed because JobQueueEventBus does not return the current
278        // job queue count.
279        $this->sha1ValuesBeingProcessed = array_merge( $this->sha1ValuesBeingProcessed, $batch );
280        // Wait until at least half of the SHA-1's have been updated to have mms_last_checked as the current date
281        // or we have looped more than --max-polls times.
282        $numberOfTimesPolled = 0;
283        if ( !count( $this->sha1ValuesBeingProcessed ) ) {
284            // Return early if sha1ValuesBeingProcessed is empty, as we have nothing to wait for.
285            return;
286        }
287        do {
288            if ( $this->hasOption( 'verbose' ) ) {
289                // If in verbose mode, print out how many jobs are currently processing and how many we are
290                // waiting to complete before adding more.
291                $sha1sBeingProcessedCount = count( $this->sha1ValuesBeingProcessed );
292                $this->output(
293                    "$sha1sBeingProcessedCount SHA-1 value(s) currently being processed via jobs. " .
294                    "Waiting until there are $pollUntil or less SHA-1 value(s) being processed before " .
295                    "adding more jobs.\n"
296                );
297            }
298            $this->sha1ValuesBeingProcessed = array_diff(
299                $this->sha1ValuesBeingProcessed, $this->pollSha1ValuesForScanCompletion()
300            );
301            sleep( intval( $this->getOption( 'poll-sleep', 1 ) ) );
302            $numberOfTimesPolled++;
303        } while (
304            count( $this->sha1ValuesBeingProcessed ) > $pollUntil &&
305            $numberOfTimesPolled < $this->getOption( 'max-polls', 60 )
306        );
307        // If the we polled too many times, then reset the internal array of SHA-1s being processed as it is probably
308        // out of sync to the actual number of jobs running.
309        if ( $numberOfTimesPolled >= $this->getOption( 'max-polls', 60 ) ) {
310            if ( $this->hasOption( 'verbose' ) ) {
311                $this->error(
312                    'The internal array of SHA-1 values being processed has been cleared as more than ' .
313                    "{$this->getOption( 'max-polls', 60 )} polls have occurred.\n"
314                );
315            }
316            $this->sha1ValuesBeingProcessed = [];
317        }
318    }
319
320    protected function pollSha1ValuesForScanCompletion(): array {
321        // If there are no SHA-1 values being processed, then we cannot poll the DB for their status as there
322        // is nothing to check.
323        if ( !count( $this->sha1ValuesBeingProcessed ) ) {
324            return [];
325        }
326        $dbr = $this->mediaModerationDatabaseLookup->getDb( IDBAccessObject::READ_NORMAL );
327        // Wait for replication to occur to avoid polling a out-of-date replica DB.
328        $this->waitForReplication();
329        $queryBuilder = $dbr->newSelectQueryBuilder()
330            ->select( 'mms_sha1' )
331            ->from( 'mediamoderation_scan' )
332            ->where( [ 'mms_sha1' => $this->sha1ValuesBeingProcessed ] );
333        if ( $this->lastChecked === null ) {
334            $queryBuilder->andWhere( $dbr->expr(
335                'mms_last_checked', '!=', null
336            ) );
337        } else {
338            $queryBuilder->andWhere( $dbr->expr(
339                'mms_last_checked',
340                '>',
341                $this->mediaModerationDatabaseLookup->getDateFromTimestamp( $this->lastChecked )
342            ) );
343        }
344        return $queryBuilder->caller( __METHOD__ )->fetchFieldValues();
345    }
346}
347
348// @codeCoverageIgnoreStart
349$maintClass = ScanFilesInScanTable::class;
350require_once RUN_MAINTENANCE_IF_MAIN;
351// @codeCoverageIgnoreEnd