PoolCounter.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. <?php
  2. /**
  3. * Provides of semaphore semantics for restricting the number
  4. * of workers that may be concurrently performing the same task.
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License along
  17. * with this program; if not, write to the Free Software Foundation, Inc.,
  18. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. * http://www.gnu.org/copyleft/gpl.html
  20. *
  21. * @file
  22. */
  23. /**
  24. * When you have many workers (threads/servers) giving service, and a
  25. * cached item expensive to produce expires, you may get several workers
  26. * doing the job at the same time.
  27. *
  28. * Given enough requests and the item expiring fast (non-cacheable,
  29. * lots of edits...) that single work can end up unfairly using most (all)
  30. * of the cpu of the pool. This is also known as 'Michael Jackson effect'
  31. * since this effect triggered on the english wikipedia on the day Michael
  32. * Jackson died, the biographical article got hit with several edits per
  33. * minutes and hundreds of read hits.
  34. *
  35. * The PoolCounter provides semaphore semantics for restricting the number
  36. * of workers that may be concurrently performing such single task. Only one
  37. * key can be locked by any PoolCounter instance of a process, except for keys
  38. * that start with "nowait:". However, only 0 timeouts (non-blocking requests)
  39. * can be used with "nowait:" keys.
  40. *
  41. * By default PoolCounter_Stub is used, which provides no locking. You
  42. * can get a useful one in the PoolCounter extension.
  43. */
  44. abstract class PoolCounter {
  45. /* Return codes */
  46. const LOCKED = 1; /* Lock acquired */
  47. const RELEASED = 2; /* Lock released */
  48. const DONE = 3; /* Another worker did the work for you */
  49. const ERROR = -1; /* Indeterminate error */
  50. const NOT_LOCKED = -2; /* Called release() with no lock held */
  51. const QUEUE_FULL = -3; /* There are already maxqueue workers on this lock */
  52. const TIMEOUT = -4; /* Timeout exceeded */
  53. const LOCK_HELD = -5; /* Cannot acquire another lock while you have one lock held */
  54. /** @var string All workers with the same key share the lock */
  55. protected $key;
  56. /** @var int Maximum number of workers working on tasks with the same key simultaneously */
  57. protected $workers;
  58. /**
  59. * Maximum number of workers working on this task type, regardless of key.
  60. * 0 means unlimited. Max allowed value is 65536.
  61. * The way the slot limit is enforced is overzealous - this option should be used with caution.
  62. * @var int
  63. */
  64. protected $slots = 0;
  65. /** @var int If this number of workers are already working/waiting, fail instead of wait */
  66. protected $maxqueue;
  67. /** @var float Maximum time in seconds to wait for the lock */
  68. protected $timeout;
  69. /**
  70. * @var bool Whether the key is a "might wait" key
  71. */
  72. private $isMightWaitKey;
  73. /**
  74. * @var bool Whether this process holds a "might wait" lock key
  75. */
  76. private static $acquiredMightWaitKey = 0;
  77. /**
  78. * @param array $conf
  79. * @param string $type The class of actions to limit concurrency for (task type)
  80. * @param string $key
  81. */
  82. protected function __construct( $conf, $type, $key ) {
  83. $this->workers = $conf['workers'];
  84. $this->maxqueue = $conf['maxqueue'];
  85. $this->timeout = $conf['timeout'];
  86. if ( isset( $conf['slots'] ) ) {
  87. $this->slots = $conf['slots'];
  88. }
  89. if ( $this->slots ) {
  90. $key = $this->hashKeyIntoSlots( $type, $key, $this->slots );
  91. }
  92. $this->key = $key;
  93. $this->isMightWaitKey = !preg_match( '/^nowait:/', $this->key );
  94. }
  95. /**
  96. * Create a Pool counter. This should only be called from the PoolWorks.
  97. *
  98. * @param string $type The class of actions to limit concurrency for (task type)
  99. * @param string $key
  100. *
  101. * @return PoolCounter
  102. */
  103. public static function factory( $type, $key ) {
  104. global $wgPoolCounterConf;
  105. if ( !isset( $wgPoolCounterConf[$type] ) ) {
  106. return new PoolCounter_Stub;
  107. }
  108. $conf = $wgPoolCounterConf[$type];
  109. $class = $conf['class'];
  110. return new $class( $conf, $type, $key );
  111. }
  112. /**
  113. * @return string
  114. */
  115. public function getKey() {
  116. return $this->key;
  117. }
  118. /**
  119. * I want to do this task and I need to do it myself.
  120. *
  121. * @return Status Value is one of Locked/Error
  122. */
  123. abstract public function acquireForMe();
  124. /**
  125. * I want to do this task, but if anyone else does it
  126. * instead, it's also fine for me. I will read its cached data.
  127. *
  128. * @return Status Value is one of Locked/Done/Error
  129. */
  130. abstract public function acquireForAnyone();
  131. /**
  132. * I have successfully finished my task.
  133. * Lets another one grab the lock, and returns the workers
  134. * waiting on acquireForAnyone()
  135. *
  136. * @return Status Value is one of Released/NotLocked/Error
  137. */
  138. abstract public function release();
  139. /**
  140. * Checks that the lock request is sane.
  141. * @return Status - good for sane requests fatal for insane
  142. * @since 1.25
  143. */
  144. final protected function precheckAcquire() {
  145. if ( $this->isMightWaitKey ) {
  146. if ( self::$acquiredMightWaitKey ) {
  147. /*
  148. * The poolcounter itself is quite happy to allow you to wait
  149. * on another lock while you have a lock you waited on already
  150. * but we think that it is unlikely to be a good idea. So we
  151. * made it an error. If you are _really_ _really_ sure it is a
  152. * good idea then feel free to implement an unsafe flag or
  153. * something.
  154. */
  155. return Status::newFatal( 'poolcounter-usage-error',
  156. 'You may only aquire a single non-nowait lock.' );
  157. }
  158. } elseif ( $this->timeout !== 0 ) {
  159. return Status::newFatal( 'poolcounter-usage-error',
  160. 'Locks starting in nowait: must have 0 timeout.' );
  161. }
  162. return Status::newGood();
  163. }
  164. /**
  165. * Update any lock tracking information when the lock is acquired
  166. * @since 1.25
  167. */
  168. final protected function onAcquire() {
  169. self::$acquiredMightWaitKey |= $this->isMightWaitKey;
  170. }
  171. /**
  172. * Update any lock tracking information when the lock is released
  173. * @since 1.25
  174. */
  175. final protected function onRelease() {
  176. self::$acquiredMightWaitKey &= !$this->isMightWaitKey;
  177. }
  178. /**
  179. * Given a key (any string) and the number of lots, returns a slot key (a prefix with a suffix
  180. * integer from the [0..($slots-1)] range). This is used for a global limit on the number of
  181. * instances of a given type that can acquire a lock. The hashing is deterministic so that
  182. * PoolCounter::$workers is always an upper limit of how many instances with the same key
  183. * can acquire a lock.
  184. *
  185. * @param string $type The class of actions to limit concurrency for (task type)
  186. * @param string $key PoolCounter instance key (any string)
  187. * @param int $slots The number of slots (max allowed value is 65536)
  188. * @return string Slot key with the type and slot number
  189. */
  190. protected function hashKeyIntoSlots( $type, $key, $slots ) {
  191. return $type . ':' . ( hexdec( substr( sha1( $key ), 0, 4 ) ) % $slots );
  192. }
  193. }
  194. // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
  195. class PoolCounter_Stub extends PoolCounter {
  196. public function __construct() {
  197. /* No parameters needed */
  198. }
  199. public function acquireForMe() {
  200. return Status::newGood( PoolCounter::LOCKED );
  201. }
  202. public function acquireForAnyone() {
  203. return Status::newGood( PoolCounter::LOCKED );
  204. }
  205. public function release() {
  206. return Status::newGood( PoolCounter::RELEASED );
  207. }
  208. }