JobQueueFederated.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. <?php
  2. /**
  3. * Job queue code for federated queues.
  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. /**
  23. * Class to handle enqueueing and running of background jobs for federated queues
  24. *
  25. * This class allows for queues to be partitioned into smaller queues.
  26. * A partition is defined by the configuration for a JobQueue instance.
  27. * For example, one can set $wgJobTypeConf['refreshLinks'] to point to a
  28. * JobQueueFederated instance, which itself would consist of three JobQueueRedis
  29. * instances, each using their own redis server. This would allow for the jobs
  30. * to be split (evenly or based on weights) across multiple servers if a single
  31. * server becomes impractical or expensive. Different JobQueue classes can be mixed.
  32. *
  33. * The basic queue configuration (e.g. "order", "claimTTL") of a federated queue
  34. * is inherited by the partition queues. Additional configuration defines what
  35. * section each wiki is in, what partition queues each section uses (and their weight),
  36. * and the JobQueue configuration for each partition. Some sections might only need a
  37. * single queue partition, like the sections for groups of small wikis.
  38. *
  39. * If used for performance, then $wgMainCacheType should be set to memcached/redis.
  40. * Note that "fifo" cannot be used for the ordering, since the data is distributed.
  41. * One can still use "timestamp" instead, as in "roughly timestamp ordered". Also,
  42. * queue classes used by this should ignore down servers (with TTL) to avoid slowness.
  43. *
  44. * @ingroup JobQueue
  45. * @since 1.22
  46. */
  47. class JobQueueFederated extends JobQueue {
  48. /** @var HashRing */
  49. protected $partitionRing;
  50. /** @var JobQueue[] (partition name => JobQueue) reverse sorted by weight */
  51. protected $partitionQueues = [];
  52. /** @var int Maximum number of partitions to try */
  53. protected $maxPartitionsTry;
  54. /**
  55. * @param array $params Possible keys:
  56. * - sectionsByWiki : A map of wiki IDs to section names.
  57. * Wikis will default to using the section "default".
  58. * - partitionsBySection : Map of section names to maps of (partition name => weight).
  59. * A section called 'default' must be defined if not all wikis
  60. * have explicitly defined sections.
  61. * - configByPartition : Map of queue partition names to configuration arrays.
  62. * These configuration arrays are passed to JobQueue::factory().
  63. * The options set here are overridden by those passed to this
  64. * the federated queue itself (e.g. 'order' and 'claimTTL').
  65. * - maxPartitionsTry : Maximum number of times to attempt job insertion using
  66. * different partition queues. This improves availability
  67. * during failure, at the cost of added latency and somewhat
  68. * less reliable job de-duplication mechanisms.
  69. * @throws MWException
  70. */
  71. protected function __construct( array $params ) {
  72. parent::__construct( $params );
  73. $section = $params['sectionsByWiki'][$this->domain] ?? 'default';
  74. if ( !isset( $params['partitionsBySection'][$section] ) ) {
  75. throw new MWException( "No configuration for section '$section'." );
  76. }
  77. $this->maxPartitionsTry = $params['maxPartitionsTry'] ?? 2;
  78. // Get the full partition map
  79. $partitionMap = $params['partitionsBySection'][$section];
  80. arsort( $partitionMap, SORT_NUMERIC );
  81. // Get the config to pass to merge into each partition queue config
  82. $baseConfig = $params;
  83. foreach ( [ 'class', 'sectionsByWiki', 'maxPartitionsTry',
  84. 'partitionsBySection', 'configByPartition', ] as $o
  85. ) {
  86. unset( $baseConfig[$o] ); // partition queue doesn't care about this
  87. }
  88. // Get the partition queue objects
  89. foreach ( $partitionMap as $partition => $w ) {
  90. if ( !isset( $params['configByPartition'][$partition] ) ) {
  91. throw new MWException( "No configuration for partition '$partition'." );
  92. }
  93. $this->partitionQueues[$partition] = JobQueue::factory(
  94. $baseConfig + $params['configByPartition'][$partition] );
  95. }
  96. // Ring of all partitions
  97. $this->partitionRing = new HashRing( $partitionMap );
  98. }
  99. protected function supportedOrders() {
  100. // No FIFO due to partitioning, though "rough timestamp order" is supported
  101. return [ 'undefined', 'random', 'timestamp' ];
  102. }
  103. protected function optimalOrder() {
  104. return 'undefined'; // defer to the partitions
  105. }
  106. protected function supportsDelayedJobs() {
  107. foreach ( $this->partitionQueues as $queue ) {
  108. if ( !$queue->supportsDelayedJobs() ) {
  109. return false;
  110. }
  111. }
  112. return true;
  113. }
  114. protected function doIsEmpty() {
  115. $empty = true;
  116. $failed = 0;
  117. foreach ( $this->partitionQueues as $queue ) {
  118. try {
  119. $empty = $empty && $queue->doIsEmpty();
  120. } catch ( JobQueueError $e ) {
  121. ++$failed;
  122. $this->logException( $e );
  123. }
  124. }
  125. $this->throwErrorIfAllPartitionsDown( $failed );
  126. return $empty;
  127. }
  128. protected function doGetSize() {
  129. return $this->getCrossPartitionSum( 'size', 'doGetSize' );
  130. }
  131. protected function doGetAcquiredCount() {
  132. return $this->getCrossPartitionSum( 'acquiredcount', 'doGetAcquiredCount' );
  133. }
  134. protected function doGetDelayedCount() {
  135. return $this->getCrossPartitionSum( 'delayedcount', 'doGetDelayedCount' );
  136. }
  137. protected function doGetAbandonedCount() {
  138. return $this->getCrossPartitionSum( 'abandonedcount', 'doGetAbandonedCount' );
  139. }
  140. /**
  141. * @param string $type
  142. * @param string $method
  143. * @return int
  144. */
  145. protected function getCrossPartitionSum( $type, $method ) {
  146. $count = 0;
  147. $failed = 0;
  148. foreach ( $this->partitionQueues as $queue ) {
  149. try {
  150. $count += $queue->$method();
  151. } catch ( JobQueueError $e ) {
  152. ++$failed;
  153. $this->logException( $e );
  154. }
  155. }
  156. $this->throwErrorIfAllPartitionsDown( $failed );
  157. return $count;
  158. }
  159. protected function doBatchPush( array $jobs, $flags ) {
  160. // Local ring variable that may be changed to point to a new ring on failure
  161. $partitionRing = $this->partitionRing;
  162. // Try to insert the jobs and update $partitionsTry on any failures.
  163. // Retry to insert any remaning jobs again, ignoring the bad partitions.
  164. $jobsLeft = $jobs;
  165. for ( $i = $this->maxPartitionsTry; $i > 0 && count( $jobsLeft ); --$i ) {
  166. try {
  167. $partitionRing->getLiveLocationWeights();
  168. } catch ( UnexpectedValueException $e ) {
  169. break; // all servers down; nothing to insert to
  170. }
  171. $jobsLeft = $this->tryJobInsertions( $jobsLeft, $partitionRing, $flags );
  172. }
  173. if ( count( $jobsLeft ) ) {
  174. throw new JobQueueError(
  175. "Could not insert job(s), {$this->maxPartitionsTry} partitions tried." );
  176. }
  177. }
  178. /**
  179. * @param array $jobs
  180. * @param HashRing &$partitionRing
  181. * @param int $flags
  182. * @throws JobQueueError
  183. * @return IJobSpecification[] List of Job object that could not be inserted
  184. */
  185. protected function tryJobInsertions( array $jobs, HashRing &$partitionRing, $flags ) {
  186. $jobsLeft = [];
  187. // Because jobs are spread across partitions, per-job de-duplication needs
  188. // to use a consistent hash to avoid allowing duplicate jobs per partition.
  189. // When inserting a batch of de-duplicated jobs, QOS_ATOMIC is disregarded.
  190. $uJobsByPartition = []; // (partition name => job list)
  191. /** @var Job $job */
  192. foreach ( $jobs as $key => $job ) {
  193. if ( $job->ignoreDuplicates() ) {
  194. $sha1 = sha1( serialize( $job->getDeduplicationInfo() ) );
  195. $uJobsByPartition[$partitionRing->getLiveLocation( $sha1 )][] = $job;
  196. unset( $jobs[$key] );
  197. }
  198. }
  199. // Get the batches of jobs that are not de-duplicated
  200. if ( $flags & self::QOS_ATOMIC ) {
  201. $nuJobBatches = [ $jobs ]; // all or nothing
  202. } else {
  203. // Split the jobs into batches and spread them out over servers if there
  204. // are many jobs. This helps keep the partitions even. Otherwise, send all
  205. // the jobs to a single partition queue to avoids the extra connections.
  206. $nuJobBatches = array_chunk( $jobs, 300 );
  207. }
  208. // Insert the de-duplicated jobs into the queues...
  209. foreach ( $uJobsByPartition as $partition => $jobBatch ) {
  210. /** @var JobQueue $queue */
  211. $queue = $this->partitionQueues[$partition];
  212. try {
  213. $ok = true;
  214. $queue->doBatchPush( $jobBatch, $flags | self::QOS_ATOMIC );
  215. } catch ( JobQueueError $e ) {
  216. $ok = false;
  217. $this->logException( $e );
  218. }
  219. if ( !$ok ) {
  220. if ( !$partitionRing->ejectFromLiveRing( $partition, 5 ) ) { // blacklist
  221. throw new JobQueueError( "Could not insert job(s), no partitions available." );
  222. }
  223. $jobsLeft = array_merge( $jobsLeft, $jobBatch ); // not inserted
  224. }
  225. }
  226. // Insert the jobs that are not de-duplicated into the queues...
  227. foreach ( $nuJobBatches as $jobBatch ) {
  228. $partition = ArrayUtils::pickRandom( $partitionRing->getLiveLocationWeights() );
  229. $queue = $this->partitionQueues[$partition];
  230. try {
  231. $ok = true;
  232. $queue->doBatchPush( $jobBatch, $flags | self::QOS_ATOMIC );
  233. } catch ( JobQueueError $e ) {
  234. $ok = false;
  235. $this->logException( $e );
  236. }
  237. if ( !$ok ) {
  238. if ( !$partitionRing->ejectFromLiveRing( $partition, 5 ) ) { // blacklist
  239. throw new JobQueueError( "Could not insert job(s), no partitions available." );
  240. }
  241. $jobsLeft = array_merge( $jobsLeft, $jobBatch ); // not inserted
  242. }
  243. }
  244. return $jobsLeft;
  245. }
  246. protected function doPop() {
  247. $partitionsTry = $this->partitionRing->getLiveLocationWeights(); // (partition => weight)
  248. $failed = 0;
  249. while ( count( $partitionsTry ) ) {
  250. $partition = ArrayUtils::pickRandom( $partitionsTry );
  251. if ( $partition === false ) {
  252. break; // all partitions at 0 weight
  253. }
  254. /** @var JobQueue $queue */
  255. $queue = $this->partitionQueues[$partition];
  256. try {
  257. $job = $queue->pop();
  258. } catch ( JobQueueError $e ) {
  259. ++$failed;
  260. $this->logException( $e );
  261. $job = false;
  262. }
  263. if ( $job ) {
  264. $job->setMetadata( 'QueuePartition', $partition );
  265. return $job;
  266. } else {
  267. unset( $partitionsTry[$partition] ); // blacklist partition
  268. }
  269. }
  270. $this->throwErrorIfAllPartitionsDown( $failed );
  271. return false;
  272. }
  273. protected function doAck( RunnableJob $job ) {
  274. $partition = $job->getMetadata( 'QueuePartition' );
  275. if ( $partition === null ) {
  276. throw new MWException( "The given job has no defined partition name." );
  277. }
  278. $this->partitionQueues[$partition]->ack( $job );
  279. }
  280. protected function doIsRootJobOldDuplicate( IJobSpecification $job ) {
  281. $signature = $job->getRootJobParams()['rootJobSignature'];
  282. $partition = $this->partitionRing->getLiveLocation( $signature );
  283. try {
  284. return $this->partitionQueues[$partition]->doIsRootJobOldDuplicate( $job );
  285. } catch ( JobQueueError $e ) {
  286. if ( $this->partitionRing->ejectFromLiveRing( $partition, 5 ) ) {
  287. $partition = $this->partitionRing->getLiveLocation( $signature );
  288. return $this->partitionQueues[$partition]->doIsRootJobOldDuplicate( $job );
  289. }
  290. }
  291. return false;
  292. }
  293. protected function doDeduplicateRootJob( IJobSpecification $job ) {
  294. $signature = $job->getRootJobParams()['rootJobSignature'];
  295. $partition = $this->partitionRing->getLiveLocation( $signature );
  296. try {
  297. return $this->partitionQueues[$partition]->doDeduplicateRootJob( $job );
  298. } catch ( JobQueueError $e ) {
  299. if ( $this->partitionRing->ejectFromLiveRing( $partition, 5 ) ) {
  300. $partition = $this->partitionRing->getLiveLocation( $signature );
  301. return $this->partitionQueues[$partition]->doDeduplicateRootJob( $job );
  302. }
  303. }
  304. return false;
  305. }
  306. protected function doDelete() {
  307. $failed = 0;
  308. /** @var JobQueue $queue */
  309. foreach ( $this->partitionQueues as $queue ) {
  310. try {
  311. $queue->doDelete();
  312. } catch ( JobQueueError $e ) {
  313. ++$failed;
  314. $this->logException( $e );
  315. }
  316. }
  317. $this->throwErrorIfAllPartitionsDown( $failed );
  318. return true;
  319. }
  320. protected function doWaitForBackups() {
  321. $failed = 0;
  322. /** @var JobQueue $queue */
  323. foreach ( $this->partitionQueues as $queue ) {
  324. try {
  325. $queue->waitForBackups();
  326. } catch ( JobQueueError $e ) {
  327. ++$failed;
  328. $this->logException( $e );
  329. }
  330. }
  331. $this->throwErrorIfAllPartitionsDown( $failed );
  332. }
  333. protected function doFlushCaches() {
  334. /** @var JobQueue $queue */
  335. foreach ( $this->partitionQueues as $queue ) {
  336. $queue->doFlushCaches();
  337. }
  338. }
  339. public function getAllQueuedJobs() {
  340. $iterator = new AppendIterator();
  341. /** @var JobQueue $queue */
  342. foreach ( $this->partitionQueues as $queue ) {
  343. $iterator->append( $queue->getAllQueuedJobs() );
  344. }
  345. return $iterator;
  346. }
  347. public function getAllDelayedJobs() {
  348. $iterator = new AppendIterator();
  349. /** @var JobQueue $queue */
  350. foreach ( $this->partitionQueues as $queue ) {
  351. $iterator->append( $queue->getAllDelayedJobs() );
  352. }
  353. return $iterator;
  354. }
  355. public function getAllAcquiredJobs() {
  356. $iterator = new AppendIterator();
  357. /** @var JobQueue $queue */
  358. foreach ( $this->partitionQueues as $queue ) {
  359. $iterator->append( $queue->getAllAcquiredJobs() );
  360. }
  361. return $iterator;
  362. }
  363. public function getAllAbandonedJobs() {
  364. $iterator = new AppendIterator();
  365. /** @var JobQueue $queue */
  366. foreach ( $this->partitionQueues as $queue ) {
  367. $iterator->append( $queue->getAllAbandonedJobs() );
  368. }
  369. return $iterator;
  370. }
  371. public function getCoalesceLocationInternal() {
  372. return "JobQueueFederated:wiki:{$this->domain}" .
  373. sha1( serialize( array_keys( $this->partitionQueues ) ) );
  374. }
  375. protected function doGetSiblingQueuesWithJobs( array $types ) {
  376. $result = [];
  377. $failed = 0;
  378. /** @var JobQueue $queue */
  379. foreach ( $this->partitionQueues as $queue ) {
  380. try {
  381. $nonEmpty = $queue->doGetSiblingQueuesWithJobs( $types );
  382. if ( is_array( $nonEmpty ) ) {
  383. $result = array_unique( array_merge( $result, $nonEmpty ) );
  384. } else {
  385. return null; // not supported on all partitions; bail
  386. }
  387. if ( count( $result ) == count( $types ) ) {
  388. break; // short-circuit
  389. }
  390. } catch ( JobQueueError $e ) {
  391. ++$failed;
  392. $this->logException( $e );
  393. }
  394. }
  395. $this->throwErrorIfAllPartitionsDown( $failed );
  396. return array_values( $result );
  397. }
  398. protected function doGetSiblingQueueSizes( array $types ) {
  399. $result = [];
  400. $failed = 0;
  401. /** @var JobQueue $queue */
  402. foreach ( $this->partitionQueues as $queue ) {
  403. try {
  404. $sizes = $queue->doGetSiblingQueueSizes( $types );
  405. if ( is_array( $sizes ) ) {
  406. foreach ( $sizes as $type => $size ) {
  407. $result[$type] = isset( $result[$type] ) ? $result[$type] + $size : $size;
  408. }
  409. } else {
  410. return null; // not supported on all partitions; bail
  411. }
  412. } catch ( JobQueueError $e ) {
  413. ++$failed;
  414. $this->logException( $e );
  415. }
  416. }
  417. $this->throwErrorIfAllPartitionsDown( $failed );
  418. return $result;
  419. }
  420. protected function logException( Exception $e ) {
  421. wfDebugLog( 'JobQueueFederated', $e->getMessage() . "\n" . $e->getTraceAsString() );
  422. }
  423. /**
  424. * Throw an error if no partitions available
  425. *
  426. * @param int $down The number of up partitions down
  427. * @return void
  428. * @throws JobQueueError
  429. */
  430. protected function throwErrorIfAllPartitionsDown( $down ) {
  431. if ( $down >= count( $this->partitionQueues ) ) {
  432. throw new JobQueueError( 'No queue partitions available.' );
  433. }
  434. }
  435. }