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