Job.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. <?php
  2. /**
  3. * Job queue task base 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. * @defgroup JobQueue JobQueue
  22. */
  23. /**
  24. * Class to both describe a background job and handle jobs.
  25. * The queue aspects of this class are now deprecated.
  26. * Using the class to push jobs onto queues is deprecated (use JobSpecification).
  27. *
  28. * @ingroup JobQueue
  29. */
  30. abstract class Job implements IJobSpecification {
  31. /** @var string */
  32. public $command;
  33. /** @var array Array of job parameters */
  34. public $params;
  35. /** @var array Additional queue metadata */
  36. public $metadata = [];
  37. /** @var Title */
  38. protected $title;
  39. /** @var bool Expensive jobs may set this to true */
  40. protected $removeDuplicates;
  41. /** @var string Text for error that occurred last */
  42. protected $error;
  43. /** @var callable[] */
  44. protected $teardownCallbacks = [];
  45. /** @var int Bitfield of JOB_* class constants */
  46. protected $executionFlags = 0;
  47. /** @var int Job must not be wrapped in the usual explicit LBFactory transaction round */
  48. const JOB_NO_EXPLICIT_TRX_ROUND = 1;
  49. /**
  50. * Run the job
  51. * @return bool Success
  52. */
  53. abstract public function run();
  54. /**
  55. * Create the appropriate object to handle a specific job
  56. *
  57. * @param string $command Job command
  58. * @param Title $title Associated title
  59. * @param array $params Job parameters
  60. * @throws MWException
  61. * @return Job
  62. */
  63. public static function factory( $command, Title $title, $params = [] ) {
  64. global $wgJobClasses;
  65. if ( isset( $wgJobClasses[$command] ) ) {
  66. $handler = $wgJobClasses[$command];
  67. if ( is_callable( $handler ) ) {
  68. $job = call_user_func( $handler, $title, $params );
  69. } elseif ( class_exists( $handler ) ) {
  70. $job = new $handler( $title, $params );
  71. } else {
  72. $job = null;
  73. }
  74. if ( $job instanceof Job ) {
  75. $job->command = $command;
  76. return $job;
  77. } else {
  78. throw new InvalidArgumentException( "Cannot instantiate job '$command': bad spec!" );
  79. }
  80. }
  81. throw new InvalidArgumentException( "Invalid job command '{$command}'" );
  82. }
  83. /**
  84. * @param string $command
  85. * @param Title $title
  86. * @param array|bool $params Can not be === true
  87. */
  88. public function __construct( $command, $title, $params = false ) {
  89. $this->command = $command;
  90. $this->title = $title;
  91. $this->params = is_array( $params ) ? $params : []; // sanity
  92. // expensive jobs may set this to true
  93. $this->removeDuplicates = false;
  94. if ( !isset( $this->params['requestId'] ) ) {
  95. $this->params['requestId'] = WebRequest::getRequestId();
  96. }
  97. }
  98. /**
  99. * @param int $flag JOB_* class constant
  100. * @return bool
  101. * @since 1.31
  102. */
  103. public function hasExecutionFlag( $flag ) {
  104. return ( $this->executionFlags && $flag ) === $flag;
  105. }
  106. /**
  107. * Batch-insert a group of jobs into the queue.
  108. * This will be wrapped in a transaction with a forced commit.
  109. *
  110. * This may add duplicate at insert time, but they will be
  111. * removed later on, when the first one is popped.
  112. *
  113. * @param Job[] $jobs Array of Job objects
  114. * @return bool
  115. * @deprecated since 1.21
  116. */
  117. public static function batchInsert( $jobs ) {
  118. wfDeprecated( __METHOD__, '1.21' );
  119. JobQueueGroup::singleton()->push( $jobs );
  120. return true;
  121. }
  122. /**
  123. * @return string
  124. */
  125. public function getType() {
  126. return $this->command;
  127. }
  128. /**
  129. * @return Title
  130. */
  131. public function getTitle() {
  132. return $this->title;
  133. }
  134. /**
  135. * @return array
  136. */
  137. public function getParams() {
  138. return $this->params;
  139. }
  140. /**
  141. * @return int|null UNIX timestamp to delay running this job until, otherwise null
  142. * @since 1.22
  143. */
  144. public function getReleaseTimestamp() {
  145. return isset( $this->params['jobReleaseTimestamp'] )
  146. ? wfTimestampOrNull( TS_UNIX, $this->params['jobReleaseTimestamp'] )
  147. : null;
  148. }
  149. /**
  150. * @return int|null UNIX timestamp of when the job was queued, or null
  151. * @since 1.26
  152. */
  153. public function getQueuedTimestamp() {
  154. return isset( $this->metadata['timestamp'] )
  155. ? wfTimestampOrNull( TS_UNIX, $this->metadata['timestamp'] )
  156. : null;
  157. }
  158. /**
  159. * @return string|null Id of the request that created this job. Follows
  160. * jobs recursively, allowing to track the id of the request that started a
  161. * job when jobs insert jobs which insert other jobs.
  162. * @since 1.27
  163. */
  164. public function getRequestId() {
  165. return isset( $this->params['requestId'] )
  166. ? $this->params['requestId']
  167. : null;
  168. }
  169. /**
  170. * @return int|null UNIX timestamp of when the job was runnable, or null
  171. * @since 1.26
  172. */
  173. public function getReadyTimestamp() {
  174. return $this->getReleaseTimestamp() ?: $this->getQueuedTimestamp();
  175. }
  176. /**
  177. * Whether the queue should reject insertion of this job if a duplicate exists
  178. *
  179. * This can be used to avoid duplicated effort or combined with delayed jobs to
  180. * coalesce updates into larger batches. Claimed jobs are never treated as
  181. * duplicates of new jobs, and some queues may allow a few duplicates due to
  182. * network partitions and fail-over. Thus, additional locking is needed to
  183. * enforce mutual exclusion if this is really needed.
  184. *
  185. * @return bool
  186. */
  187. public function ignoreDuplicates() {
  188. return $this->removeDuplicates;
  189. }
  190. /**
  191. * @return bool Whether this job can be retried on failure by job runners
  192. * @since 1.21
  193. */
  194. public function allowRetries() {
  195. return true;
  196. }
  197. /**
  198. * @return int Number of actually "work items" handled in this job
  199. * @see $wgJobBackoffThrottling
  200. * @since 1.23
  201. */
  202. public function workItemCount() {
  203. return 1;
  204. }
  205. /**
  206. * Subclasses may need to override this to make duplication detection work.
  207. * The resulting map conveys everything that makes the job unique. This is
  208. * only checked if ignoreDuplicates() returns true, meaning that duplicate
  209. * jobs are supposed to be ignored.
  210. *
  211. * @return array Map of key/values
  212. * @since 1.21
  213. */
  214. public function getDeduplicationInfo() {
  215. $info = [
  216. 'type' => $this->getType(),
  217. 'namespace' => $this->getTitle()->getNamespace(),
  218. 'title' => $this->getTitle()->getDBkey(),
  219. 'params' => $this->getParams()
  220. ];
  221. if ( is_array( $info['params'] ) ) {
  222. // Identical jobs with different "root" jobs should count as duplicates
  223. unset( $info['params']['rootJobSignature'] );
  224. unset( $info['params']['rootJobTimestamp'] );
  225. // Likewise for jobs with different delay times
  226. unset( $info['params']['jobReleaseTimestamp'] );
  227. // Identical jobs from different requests should count as duplicates
  228. unset( $info['params']['requestId'] );
  229. // Queues pack and hash this array, so normalize the order
  230. ksort( $info['params'] );
  231. }
  232. return $info;
  233. }
  234. /**
  235. * Get "root job" parameters for a task
  236. *
  237. * This is used to no-op redundant jobs, including child jobs of jobs,
  238. * as long as the children inherit the root job parameters. When a job
  239. * with root job parameters and "rootJobIsSelf" set is pushed, the
  240. * deduplicateRootJob() method is automatically called on it. If the
  241. * root job is only virtual and not actually pushed (e.g. the sub-jobs
  242. * are inserted directly), then call deduplicateRootJob() directly.
  243. *
  244. * @see JobQueue::deduplicateRootJob()
  245. *
  246. * @param string $key A key that identifies the task
  247. * @return array Map of:
  248. * - rootJobIsSelf : true
  249. * - rootJobSignature : hash (e.g. SHA1) that identifies the task
  250. * - rootJobTimestamp : TS_MW timestamp of this instance of the task
  251. * @since 1.21
  252. */
  253. public static function newRootJobParams( $key ) {
  254. return [
  255. 'rootJobIsSelf' => true,
  256. 'rootJobSignature' => sha1( $key ),
  257. 'rootJobTimestamp' => wfTimestampNow()
  258. ];
  259. }
  260. /**
  261. * @see JobQueue::deduplicateRootJob()
  262. * @return array
  263. * @since 1.21
  264. */
  265. public function getRootJobParams() {
  266. return [
  267. 'rootJobSignature' => isset( $this->params['rootJobSignature'] )
  268. ? $this->params['rootJobSignature']
  269. : null,
  270. 'rootJobTimestamp' => isset( $this->params['rootJobTimestamp'] )
  271. ? $this->params['rootJobTimestamp']
  272. : null
  273. ];
  274. }
  275. /**
  276. * @see JobQueue::deduplicateRootJob()
  277. * @return bool
  278. * @since 1.22
  279. */
  280. public function hasRootJobParams() {
  281. return isset( $this->params['rootJobSignature'] )
  282. && isset( $this->params['rootJobTimestamp'] );
  283. }
  284. /**
  285. * @see JobQueue::deduplicateRootJob()
  286. * @return bool Whether this is job is a root job
  287. */
  288. public function isRootJob() {
  289. return $this->hasRootJobParams() && !empty( $this->params['rootJobIsSelf'] );
  290. }
  291. /**
  292. * @param callable $callback A function with one parameter, the success status, which will be
  293. * false if the job failed or it succeeded but the DB changes could not be committed or
  294. * any deferred updates threw an exception. (This parameter was added in 1.28.)
  295. * @since 1.27
  296. */
  297. protected function addTeardownCallback( $callback ) {
  298. $this->teardownCallbacks[] = $callback;
  299. }
  300. /**
  301. * Do any final cleanup after run(), deferred updates, and all DB commits happen
  302. * @param bool $status Whether the job, its deferred updates, and DB commit all succeeded
  303. * @since 1.27
  304. */
  305. public function teardown( $status ) {
  306. foreach ( $this->teardownCallbacks as $callback ) {
  307. call_user_func( $callback, $status );
  308. }
  309. }
  310. /**
  311. * Insert a single job into the queue.
  312. * @return bool True on success
  313. * @deprecated since 1.21
  314. */
  315. public function insert() {
  316. wfDeprecated( __METHOD__, '1.21' );
  317. JobQueueGroup::singleton()->push( $this );
  318. return true;
  319. }
  320. /**
  321. * @return string
  322. */
  323. public function toString() {
  324. $paramString = '';
  325. if ( $this->params ) {
  326. foreach ( $this->params as $key => $value ) {
  327. if ( $paramString != '' ) {
  328. $paramString .= ' ';
  329. }
  330. if ( is_array( $value ) ) {
  331. $filteredValue = [];
  332. foreach ( $value as $k => $v ) {
  333. $json = FormatJson::encode( $v );
  334. if ( $json === false || mb_strlen( $json ) > 512 ) {
  335. $filteredValue[$k] = gettype( $v ) . '(...)';
  336. } else {
  337. $filteredValue[$k] = $v;
  338. }
  339. }
  340. if ( count( $filteredValue ) <= 10 ) {
  341. $value = FormatJson::encode( $filteredValue );
  342. } else {
  343. $value = "array(" . count( $value ) . ")";
  344. }
  345. } elseif ( is_object( $value ) && !method_exists( $value, '__toString' ) ) {
  346. $value = "object(" . get_class( $value ) . ")";
  347. }
  348. $flatValue = (string)$value;
  349. if ( mb_strlen( $value ) > 1024 ) {
  350. $flatValue = "string(" . mb_strlen( $value ) . ")";
  351. }
  352. $paramString .= "$key={$flatValue}";
  353. }
  354. }
  355. $metaString = '';
  356. foreach ( $this->metadata as $key => $value ) {
  357. if ( is_scalar( $value ) && mb_strlen( $value ) < 1024 ) {
  358. $metaString .= ( $metaString ? ",$key=$value" : "$key=$value" );
  359. }
  360. }
  361. $s = $this->command;
  362. if ( is_object( $this->title ) ) {
  363. $s .= " {$this->title->getPrefixedDBkey()}";
  364. }
  365. if ( $paramString != '' ) {
  366. $s .= " $paramString";
  367. }
  368. if ( $metaString != '' ) {
  369. $s .= " ($metaString)";
  370. }
  371. return $s;
  372. }
  373. protected function setLastError( $error ) {
  374. $this->error = $error;
  375. }
  376. public function getLastError() {
  377. return $this->error;
  378. }
  379. }