Merge "Add 3D filetype for STL files"
[lhc/web/wiklou.git] / includes / deferred / DeferredUpdates.php
1 <?php
2 /**
3 * Interface and manager for deferred updates.
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 */
22 use Wikimedia\Rdbms\IDatabase;
23 use MediaWiki\MediaWikiServices;
24 use Wikimedia\Rdbms\LBFactory;
25 use Wikimedia\Rdbms\LoadBalancer;
26
27 /**
28 * Class for managing the deferred updates
29 *
30 * In web request mode, deferred updates can be run at the end of the request, either before or
31 * after the HTTP response has been sent. In either case, they run after the DB commit step. If
32 * an update runs after the response is sent, it will not block clients. If sent before, it will
33 * run synchronously. These two modes are defined via PRESEND and POSTSEND constants, the latter
34 * being the default for addUpdate() and addCallableUpdate().
35 *
36 * Updates that work through this system will be more likely to complete by the time the client
37 * makes their next request after this one than with the JobQueue system.
38 *
39 * In CLI mode, updates run immediately if no DB writes are pending. Otherwise, they run when:
40 * - a) Any waitForReplication() call if no writes are pending on any DB
41 * - b) A commit happens on Maintenance::getDB( DB_MASTER ) if no writes are pending on any DB
42 * - c) EnqueueableDataUpdate tasks may enqueue on commit of Maintenance::getDB( DB_MASTER )
43 * - d) At the completion of Maintenance::execute()
44 *
45 * When updates are deferred, they go into one two FIFO "top-queues" (one for pre-send and one
46 * for post-send). Updates enqueued *during* doUpdate() of a "top" update go into the "sub-queue"
47 * for that update. After that method finishes, the sub-queue is run until drained. This continues
48 * for each top-queue job until the entire top queue is drained. This happens for the pre-send
49 * top-queue, and later on, the post-send top-queue, in execute().
50 *
51 * @since 1.19
52 */
53 class DeferredUpdates {
54 /** @var DeferrableUpdate[] Updates to be deferred until before request end */
55 private static $preSendUpdates = [];
56 /** @var DeferrableUpdate[] Updates to be deferred until after request end */
57 private static $postSendUpdates = [];
58
59 const ALL = 0; // all updates; in web requests, use only after flushing the output buffer
60 const PRESEND = 1; // for updates that should run before flushing output buffer
61 const POSTSEND = 2; // for updates that should run after flushing output buffer
62
63 const BIG_QUEUE_SIZE = 100;
64
65 /** @var array|null Information about the current execute() call or null if not running */
66 private static $executeContext;
67
68 /**
69 * Add an update to the deferred list to be run later by execute()
70 *
71 * In CLI mode, callback magic will also be used to run updates when safe
72 *
73 * @param DeferrableUpdate $update Some object that implements doUpdate()
74 * @param integer $stage DeferredUpdates constant (PRESEND or POSTSEND) (since 1.27)
75 */
76 public static function addUpdate( DeferrableUpdate $update, $stage = self::POSTSEND ) {
77 global $wgCommandLineMode;
78
79 // This is a sub-DeferredUpdate, run it right after its parent update
80 if ( self::$executeContext && self::$executeContext['stage'] >= $stage ) {
81 self::$executeContext['subqueue'][] = $update;
82 return;
83 }
84
85 if ( $stage === self::PRESEND ) {
86 self::push( self::$preSendUpdates, $update );
87 } else {
88 self::push( self::$postSendUpdates, $update );
89 }
90
91 // Try to run the updates now if in CLI mode and no transaction is active.
92 // This covers scripts that don't/barely use the DB but make updates to other stores.
93 if ( $wgCommandLineMode ) {
94 self::tryOpportunisticExecute( 'run' );
95 }
96 }
97
98 /**
99 * Add a callable update. In a lot of cases, we just need a callback/closure,
100 * defining a new DeferrableUpdate object is not necessary
101 *
102 * @see MWCallableUpdate::__construct()
103 *
104 * @param callable $callable
105 * @param integer $stage DeferredUpdates constant (PRESEND or POSTSEND) (since 1.27)
106 * @param IDatabase|null $dbw Abort if this DB is rolled back [optional] (since 1.28)
107 */
108 public static function addCallableUpdate(
109 $callable, $stage = self::POSTSEND, IDatabase $dbw = null
110 ) {
111 self::addUpdate( new MWCallableUpdate( $callable, wfGetCaller(), $dbw ), $stage );
112 }
113
114 /**
115 * Do any deferred updates and clear the list
116 *
117 * @param string $mode Use "enqueue" to use the job queue when possible [Default: "run"]
118 * @param integer $stage DeferredUpdates constant (PRESEND, POSTSEND, or ALL) (since 1.27)
119 */
120 public static function doUpdates( $mode = 'run', $stage = self::ALL ) {
121 $stageEffective = ( $stage === self::ALL ) ? self::POSTSEND : $stage;
122
123 if ( $stage === self::ALL || $stage === self::PRESEND ) {
124 self::execute( self::$preSendUpdates, $mode, $stageEffective );
125 }
126
127 if ( $stage === self::ALL || $stage == self::POSTSEND ) {
128 self::execute( self::$postSendUpdates, $mode, $stageEffective );
129 }
130 }
131
132 /**
133 * @param bool $value Whether to just immediately run updates in addUpdate()
134 * @since 1.28
135 * @deprecated 1.29 Causes issues in Web-executed jobs - see T165714 and T100085.
136 */
137 public static function setImmediateMode( $value ) {
138 wfDeprecated( __METHOD__, '1.29' );
139 }
140
141 /**
142 * @param DeferrableUpdate[] $queue
143 * @param DeferrableUpdate $update
144 */
145 private static function push( array &$queue, DeferrableUpdate $update ) {
146 if ( $update instanceof MergeableUpdate ) {
147 $class = get_class( $update ); // fully-qualified class
148 if ( isset( $queue[$class] ) ) {
149 /** @var $existingUpdate MergeableUpdate */
150 $existingUpdate = $queue[$class];
151 $existingUpdate->merge( $update );
152 } else {
153 $queue[$class] = $update;
154 }
155 } else {
156 $queue[] = $update;
157 }
158 }
159
160 /**
161 * Immediately run/queue a list of updates
162 *
163 * @param DeferrableUpdate[] &$queue List of DeferrableUpdate objects
164 * @param string $mode Use "enqueue" to use the job queue when possible
165 * @param integer $stage Class constant (PRESEND, POSTSEND) (since 1.28)
166 * @throws ErrorPageError Happens on top-level calls
167 * @throws Exception Happens on second-level calls
168 */
169 protected static function execute( array &$queue, $mode, $stage ) {
170 $services = MediaWikiServices::getInstance();
171 $stats = $services->getStatsdDataFactory();
172 $lbFactory = $services->getDBLoadBalancerFactory();
173 $method = RequestContext::getMain()->getRequest()->getMethod();
174
175 $ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__ );
176
177 /** @var ErrorPageError $reportableError */
178 $reportableError = null;
179 /** @var DeferrableUpdate[] $updates Snapshot of queue */
180 $updates = $queue;
181
182 // Keep doing rounds of updates until none get enqueued...
183 while ( $updates ) {
184 $queue = []; // clear the queue
185
186 if ( $mode === 'enqueue' ) {
187 try {
188 // Push enqueuable updates to the job queue and get the rest
189 $updates = self::enqueueUpdates( $updates );
190 } catch ( Exception $e ) {
191 // Let other updates have a chance to run if this failed
192 MWExceptionHandler::rollbackMasterChangesAndLog( $e );
193 }
194 }
195
196 // Order will be DataUpdate followed by generic DeferrableUpdate tasks
197 $updatesByType = [ 'data' => [], 'generic' => [] ];
198 foreach ( $updates as $du ) {
199 if ( $du instanceof DataUpdate ) {
200 $du->setTransactionTicket( $ticket );
201 $updatesByType['data'][] = $du;
202 } else {
203 $updatesByType['generic'][] = $du;
204 }
205
206 $name = ( $du instanceof DeferrableCallback )
207 ? get_class( $du ) . '-' . $du->getOrigin()
208 : get_class( $du );
209 $stats->increment( 'deferred_updates.' . $method . '.' . $name );
210 }
211
212 // Execute all remaining tasks...
213 foreach ( $updatesByType as $updatesForType ) {
214 foreach ( $updatesForType as $update ) {
215 self::$executeContext = [
216 'update' => $update,
217 'stage' => $stage,
218 'subqueue' => []
219 ];
220 /** @var DeferrableUpdate $update */
221 $guiError = self::runUpdate( $update, $lbFactory, $stage );
222 $reportableError = $reportableError ?: $guiError;
223 // Do the subqueue updates for $update until there are none
224 while ( self::$executeContext['subqueue'] ) {
225 $subUpdate = reset( self::$executeContext['subqueue'] );
226 $firstKey = key( self::$executeContext['subqueue'] );
227 unset( self::$executeContext['subqueue'][$firstKey] );
228
229 if ( $subUpdate instanceof DataUpdate ) {
230 $subUpdate->setTransactionTicket( $ticket );
231 }
232
233 $guiError = self::runUpdate( $subUpdate, $lbFactory, $stage );
234 $reportableError = $reportableError ?: $guiError;
235 }
236 self::$executeContext = null;
237 }
238 }
239
240 $updates = $queue; // new snapshot of queue (check for new entries)
241 }
242
243 if ( $reportableError ) {
244 throw $reportableError; // throw the first of any GUI errors
245 }
246 }
247
248 /**
249 * @param DeferrableUpdate $update
250 * @param LBFactory $lbFactory
251 * @param integer $stage
252 * @return ErrorPageError|null
253 */
254 private static function runUpdate( DeferrableUpdate $update, LBFactory $lbFactory, $stage ) {
255 $guiError = null;
256 try {
257 $fnameTrxOwner = get_class( $update ) . '::doUpdate';
258 $lbFactory->beginMasterChanges( $fnameTrxOwner );
259 $update->doUpdate();
260 $lbFactory->commitMasterChanges( $fnameTrxOwner );
261 } catch ( Exception $e ) {
262 // Reporting GUI exceptions does not work post-send
263 if ( $e instanceof ErrorPageError && $stage === self::PRESEND ) {
264 $guiError = $e;
265 }
266 MWExceptionHandler::rollbackMasterChangesAndLog( $e );
267 }
268
269 return $guiError;
270 }
271
272 /**
273 * Run all deferred updates immediately if there are no DB writes active
274 *
275 * If $mode is 'run' but there are busy databates, EnqueueableDataUpdate
276 * tasks will be enqueued anyway for the sake of progress.
277 *
278 * @param string $mode Use "enqueue" to use the job queue when possible
279 * @return bool Whether updates were allowed to run
280 * @since 1.28
281 */
282 public static function tryOpportunisticExecute( $mode = 'run' ) {
283 // execute() loop is already running
284 if ( self::$executeContext ) {
285 return false;
286 }
287
288 // Avoiding running updates without them having outer scope
289 if ( !self::areDatabaseTransactionsActive() ) {
290 self::doUpdates( $mode );
291 return true;
292 }
293
294 if ( self::pendingUpdatesCount() >= self::BIG_QUEUE_SIZE ) {
295 // If we cannot run the updates with outer transaction context, try to
296 // at least enqueue all the updates that support queueing to job queue
297 self::$preSendUpdates = self::enqueueUpdates( self::$preSendUpdates );
298 self::$postSendUpdates = self::enqueueUpdates( self::$postSendUpdates );
299 }
300
301 return !self::pendingUpdatesCount();
302 }
303
304 /**
305 * Enqueue a job for each EnqueueableDataUpdate item and return the other items
306 *
307 * @param DeferrableUpdate[] $updates A list of deferred update instances
308 * @return DeferrableUpdate[] Remaining updates that do not support being queued
309 */
310 private static function enqueueUpdates( array $updates ) {
311 $remaining = [];
312
313 foreach ( $updates as $update ) {
314 if ( $update instanceof EnqueueableDataUpdate ) {
315 $spec = $update->getAsJobSpecification();
316 JobQueueGroup::singleton( $spec['wiki'] )->push( $spec['job'] );
317 } else {
318 $remaining[] = $update;
319 }
320 }
321
322 return $remaining;
323 }
324
325 /**
326 * @return integer Number of enqueued updates
327 * @since 1.28
328 */
329 public static function pendingUpdatesCount() {
330 return count( self::$preSendUpdates ) + count( self::$postSendUpdates );
331 }
332
333 /**
334 * @param integer $stage DeferredUpdates constant (PRESEND, POSTSEND, or ALL)
335 * @return DeferrableUpdate[]
336 * @since 1.29
337 */
338 public static function getPendingUpdates( $stage = self::ALL ) {
339 $updates = [];
340 if ( $stage === self::ALL || $stage === self::PRESEND ) {
341 $updates = array_merge( $updates, self::$preSendUpdates );
342 }
343 if ( $stage === self::ALL || $stage === self::POSTSEND ) {
344 $updates = array_merge( $updates, self::$postSendUpdates );
345 }
346 return $updates;
347 }
348
349 /**
350 * Clear all pending updates without performing them. Generally, you don't
351 * want or need to call this. Unit tests need it though.
352 */
353 public static function clearPendingUpdates() {
354 self::$preSendUpdates = [];
355 self::$postSendUpdates = [];
356 }
357
358 /**
359 * @return bool If a transaction round is active or connection is not ready for commit()
360 */
361 private static function areDatabaseTransactionsActive() {
362 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
363 if ( $lbFactory->hasTransactionRound() ) {
364 return true;
365 }
366
367 $connsBusy = false;
368 $lbFactory->forEachLB( function ( LoadBalancer $lb ) use ( &$connsBusy ) {
369 $lb->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$connsBusy ) {
370 if ( $conn->writesOrCallbacksPending() || $conn->explicitTrxActive() ) {
371 $connsBusy = true;
372 }
373 } );
374 } );
375
376 return $connsBusy;
377 }
378 }