Merge "CologneBlue rewrite: output the sidebar items as <ul> lists"
[lhc/web/wiklou.git] / includes / job / JobQueueDB.php
1 <?php
2 /**
3 * Database-backed job queue code.
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 * @author Aaron Schulz
22 */
23
24 /**
25 * Class to handle job queues stored in the DB
26 *
27 * @ingroup JobQueue
28 * @since 1.20
29 */
30 class JobQueueDB extends JobQueue {
31 const CACHE_TTL = 30; // integer; seconds
32 const MAX_JOB_RANDOM = 2147483647; // 2^31 - 1; used for job_random
33
34 /**
35 * @see JobQueue::doIsEmpty()
36 * @return bool
37 */
38 protected function doIsEmpty() {
39 global $wgMemc;
40
41 $key = $this->getEmptinessCacheKey();
42
43 $isEmpty = $wgMemc->get( $key );
44 if ( $isEmpty === 'true' ) {
45 return true;
46 } elseif ( $isEmpty === 'false' ) {
47 return false;
48 }
49
50 $found = $this->getSlaveDB()->selectField(
51 'job', '1', array( 'job_cmd' => $this->type ), __METHOD__
52 );
53
54 $wgMemc->add( $key, $found ? 'false' : 'true', self::CACHE_TTL );
55 }
56
57 /**
58 * @see JobQueue::doBatchPush()
59 * @return bool
60 */
61 protected function doBatchPush( array $jobs, $flags ) {
62 if ( count( $jobs ) ) {
63 $dbw = $this->getMasterDB();
64
65 $rows = array();
66 foreach ( $jobs as $job ) {
67 $rows[] = $this->insertFields( $job );
68 }
69 $atomic = ( $flags & self::QoS_Atomic );
70 $key = $this->getEmptinessCacheKey();
71 $ttl = self::CACHE_TTL;
72
73 $dbw->onTransactionIdle( function() use ( $dbw, $rows, $atomic, $key, $ttl ) {
74 global $wgMemc;
75
76 $autoTrx = $dbw->getFlag( DBO_TRX ); // automatic begin() enabled?
77 if ( $atomic ) {
78 $dbw->begin(); // wrap all the job additions in one transaction
79 } else {
80 $dbw->clearFlag( DBO_TRX ); // make each query its own transaction
81 }
82 try {
83 foreach ( array_chunk( $rows, 50 ) as $rowBatch ) { // avoid slave lag
84 $dbw->insert( 'job', $rowBatch, __METHOD__ );
85 }
86 } catch ( DBError $e ) {
87 if ( $atomic ) {
88 $dbw->rollback();
89 } else {
90 $dbw->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
91 }
92 throw $e;
93 }
94 if ( $atomic ) {
95 $dbw->commit();
96 } else {
97 $dbw->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
98 }
99
100 $wgMemc->set( $key, 'false', $ttl );
101 } );
102 }
103
104 return true;
105 }
106
107 /**
108 * @see JobQueue::doPop()
109 * @return Job|bool
110 */
111 protected function doPop() {
112 global $wgMemc;
113
114 if ( $wgMemc->get( $this->getEmptinessCacheKey() ) === 'true' ) {
115 return false; // queue is empty
116 }
117
118 $dbw = $this->getMasterDB();
119 $dbw->commit( __METHOD__, 'flush' ); // flush existing transaction
120
121 $uuid = wfRandomString( 32 ); // pop attempt
122 $job = false; // job popped off
123 $autoTrx = $dbw->getFlag( DBO_TRX ); // automatic begin() enabled?
124 $dbw->clearFlag( DBO_TRX ); // make each query its own transaction
125 try {
126 do { // retry when our row is invalid or deleted as a duplicate
127 // Try to reserve a row in the DB...
128 if ( $this->order === 'timestamp' ) { // oldest first
129 $found = $this->claim( $uuid, 0, true );
130 } else { // random first
131 $rand = mt_rand( 0, self::MAX_JOB_RANDOM ); // encourage concurrent UPDATEs
132 $gte = (bool)mt_rand( 0, 1 ); // find rows with rand before/after $rand
133 $found = $this->claim( $uuid, $rand, $gte )
134 || $this->claim( $uuid, $rand, !$gte ); // try both directions
135 }
136 // Check if we found a row to reserve...
137 if ( !$found ) {
138 $wgMemc->set( $this->getEmptinessCacheKey(), 'true', self::CACHE_TTL );
139 break; // nothing to do
140 }
141 // Fetch any row that we just reserved...
142 $row = $dbw->selectRow( 'job', '*',
143 array( 'job_cmd' => $this->type, 'job_token' => $uuid ), __METHOD__ );
144 // Check if another process deleted it as a duplicate
145 if ( !$row ) {
146 wfDebugLog( 'JobQueueDB', "Row deleted as duplicate by another process." );
147 continue; // try again
148 }
149 // Get the job object from the row...
150 $title = Title::makeTitleSafe( $row->job_namespace, $row->job_title );
151 if ( !$title ) {
152 $dbw->delete( 'job', array( 'job_id' => $row->job_id ), __METHOD__ );
153 wfDebugLog( 'JobQueueDB', "Row has invalid title '{$row->job_title}'." );
154 continue; // try again
155 }
156 $job = Job::factory( $row->job_cmd, $title,
157 self::extractBlob( $row->job_params ), $row->job_id );
158 // Delete any *other* duplicate jobs in the queue...
159 if ( $job->ignoreDuplicates() && strlen( $row->job_sha1 ) ) {
160 $dbw->delete( 'job',
161 array( 'job_sha1' => $row->job_sha1,
162 "job_id != {$dbw->addQuotes( $row->job_id )}" ),
163 __METHOD__
164 );
165 }
166 break; // done
167 } while( true );
168 } catch ( DBError $e ) {
169 $dbw->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
170 throw $e;
171 }
172 $dbw->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
173
174 return $job;
175 }
176
177 /**
178 * Reserve a row with a single UPDATE without holding row locks over RTTs...
179 * @param $uuid string 32 char hex string
180 * @param $rand integer Random unsigned integer (31 bits)
181 * @param $gte bool Search for job_random >= $random (otherwise job_random <= $random)
182 * @return integer Number of affected rows
183 */
184 protected function claim( $uuid, $rand, $gte ) {
185 $dbw = $this->getMasterDB();
186 $dir = $gte ? 'ASC' : 'DESC';
187 $ineq = $gte ? '>=' : '<=';
188 if ( $dbw->getType() === 'mysql' ) {
189 // Per http://bugs.mysql.com/bug.php?id=6980, we can't use subqueries on the
190 // same table being changed in an UPDATE query in MySQL (gives Error: 1093).
191 // Oracle and Postgre have no such limitation. However, MySQL offers an
192 // alternative here by supporting ORDER BY + LIMIT for UPDATE queries.
193 // The DB wrapper functions do not support this, so it's done manually.
194 $dbw->query( "UPDATE {$dbw->tableName( 'job' )}
195 SET
196 job_token = {$dbw->addQuotes( $uuid ) },
197 job_token_timestamp = {$dbw->addQuotes( $dbw->timestamp() )}
198 WHERE (
199 job_cmd = {$dbw->addQuotes( $this->type )}
200 AND job_token = {$dbw->addQuotes( '' )}
201 AND job_random {$ineq} {$dbw->addQuotes( $rand )}
202 ) ORDER BY job_random {$dir} LIMIT 1",
203 __METHOD__
204 );
205 } else {
206 // Use a subquery to find the job, within an UPDATE to claim it.
207 // This uses as much of the DB wrapper functions as possible.
208 $dbw->update( 'job',
209 array( 'job_token' => $uuid, 'job_token_timestamp' => $dbw->timestamp() ),
210 array( 'job_id = (' .
211 $dbw->selectSQLText( 'job', 'job_id',
212 array(
213 'job_cmd' => $this->type,
214 'job_token' => '',
215 "job_random {$ineq} {$dbw->addQuotes( $rand )}" ),
216 __METHOD__,
217 array( 'ORDER BY' => "job_random {$dir}", 'LIMIT' => 1 ) ) .
218 ')'
219 ),
220 __METHOD__
221 );
222 }
223 return $dbw->affectedRows();
224 }
225
226 /**
227 * @see JobQueue::doAck()
228 * @return Job|bool
229 */
230 protected function doAck( Job $job ) {
231 $dbw = $this->getMasterDB();
232 if ( $dbw->trxLevel() ) {
233 wfWarn( "Attempted to ack a job in a transaction; committing first." );
234 $dbw->commit(); // push existing transaction
235 }
236
237 $autoTrx = $dbw->getFlag( DBO_TRX ); // automatic begin() enabled?
238 $dbw->clearFlag( DBO_TRX ); // make each query its own transaction
239 try {
240 // Delete a row with a single DELETE without holding row locks over RTTs...
241 $dbw->delete( 'job', array( 'job_cmd' => $this->type, 'job_id' => $job->getId() ) );
242 } catch ( Exception $e ) {
243 $dbw->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
244 throw $e;
245 }
246 $dbw->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
247
248 return true;
249 }
250
251 /**
252 * @see JobQueue::doWaitForBackups()
253 * @return void
254 */
255 protected function doWaitForBackups() {
256 wfWaitForSlaves();
257 }
258
259 /**
260 * @return DatabaseBase
261 */
262 protected function getSlaveDB() {
263 return wfGetDB( DB_SLAVE, array(), $this->wiki );
264 }
265
266 /**
267 * @return DatabaseBase
268 */
269 protected function getMasterDB() {
270 return wfGetDB( DB_MASTER, array(), $this->wiki );
271 }
272
273 /**
274 * @param $job Job
275 * @return array
276 */
277 protected function insertFields( Job $job ) {
278 // Rows that describe the nature of the job
279 $descFields = array(
280 'job_cmd' => $job->getType(),
281 'job_namespace' => $job->getTitle()->getNamespace(),
282 'job_title' => $job->getTitle()->getDBkey(),
283 'job_params' => self::makeBlob( $job->getParams() ),
284 );
285 // Additional job metadata
286 if ( $this->order === 'timestamp' ) { // oldest first
287 $random = time() - 1325376000; // seconds since "January 1, 2012"
288 } else { // random first
289 $random = mt_rand( 0, self::MAX_JOB_RANDOM );
290 }
291 $dbw = $this->getMasterDB();
292 $metaFields = array(
293 'job_id' => $dbw->nextSequenceValue( 'job_job_id_seq' ),
294 'job_timestamp' => $dbw->timestamp(),
295 'job_sha1' => wfBaseConvert( sha1( serialize( $descFields ) ), 16, 36, 32 ),
296 'job_random' => mt_rand( 0, self::MAX_JOB_RANDOM )
297 );
298 return ( $descFields + $metaFields );
299 }
300
301 /**
302 * @return string
303 */
304 private function getEmptinessCacheKey() {
305 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
306 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type, 'isempty' );
307 }
308
309 /**
310 * @param $params
311 * @return string
312 */
313 protected static function makeBlob( $params ) {
314 if ( $params !== false ) {
315 return serialize( $params );
316 } else {
317 return '';
318 }
319 }
320
321 /**
322 * @param $blob
323 * @return bool|mixed
324 */
325 protected static function extractBlob( $blob ) {
326 if ( (string)$blob !== '' ) {
327 return unserialize( $blob );
328 } else {
329 return false;
330 }
331 }
332 }