queuemanager.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. <?php
  2. /**
  3. * StatusNet, the distributed open-source microblogging tool
  4. *
  5. * Abstract class for i/o managers
  6. *
  7. * PHP version 5
  8. *
  9. * LICENCE: This program is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU Affero General Public License as published by
  11. * the Free Software Foundation, either version 3 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU Affero General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU Affero General Public License
  20. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  21. *
  22. * @category QueueManager
  23. * @package StatusNet
  24. * @author Evan Prodromou <evan@status.net>
  25. * @author Sarven Capadisli <csarven@status.net>
  26. * @author Brion Vibber <brion@status.net>
  27. * @copyright 2009-2010 StatusNet, Inc.
  28. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
  29. * @link http://status.net/
  30. */
  31. /**
  32. * Completed child classes must implement the enqueue() method.
  33. *
  34. * For background processing, classes should implement either socket-based
  35. * input (handleInput(), getSockets()) or idle-loop polling (idle()).
  36. */
  37. abstract class QueueManager extends IoManager
  38. {
  39. static $qm = null;
  40. protected $master = null;
  41. protected $handlers = array();
  42. protected $groups = array();
  43. protected $activeGroups = array();
  44. protected $ignoredTransports = array();
  45. /**
  46. * Factory function to pull the appropriate QueueManager object
  47. * for this site's configuration. It can then be used to queue
  48. * events for later processing or to spawn a processing loop.
  49. *
  50. * Plugins can add to the built-in types by hooking StartNewQueueManager.
  51. *
  52. * @return QueueManager
  53. */
  54. public static function get()
  55. {
  56. if (empty(self::$qm)) {
  57. if (Event::handle('StartNewQueueManager', array(&self::$qm))) {
  58. common_log(LOG_ERR, 'Some form of queue manager must be active' .
  59. '(UnQueue does everything immediately and is the default)');
  60. throw new ServerException('Some form of queue manager must be active');
  61. }
  62. }
  63. return self::$qm;
  64. }
  65. /**
  66. * @fixme wouldn't necessarily work with other class types.
  67. * Better to change the interface...?
  68. */
  69. public static function multiSite()
  70. {
  71. if (common_config('queue', 'subsystem') == 'stomp') {
  72. return IoManager::INSTANCE_PER_PROCESS;
  73. } else {
  74. return IoManager::SINGLE_ONLY;
  75. }
  76. }
  77. function __construct()
  78. {
  79. $this->initialize();
  80. }
  81. /**
  82. * Optional; ping any running queue handler daemons with a notification
  83. * such as announcing a new site to handle or requesting clean shutdown.
  84. * This avoids having to restart all the daemons manually to update configs
  85. * and such.
  86. *
  87. * Called from scripts/queuectl.php controller utility.
  88. *
  89. * @param string $event event key
  90. * @param string $param optional parameter to append to key
  91. * @return boolean success
  92. */
  93. public function sendControlSignal($event, $param='')
  94. {
  95. throw new Exception(get_class($this) . " does not support control signals.");
  96. }
  97. /**
  98. * Store an object (usually/always a Notice) into the given queue
  99. * for later processing. No guarantee is made on when it will be
  100. * processed; it could be immediately or at some unspecified point
  101. * in the future.
  102. *
  103. * Must be implemented by any queue manager.
  104. *
  105. * @param mixed $object
  106. * @param string $queue
  107. */
  108. abstract function enqueue($object, $queue);
  109. /**
  110. * Build a representation for an object for logging
  111. * @param mixed
  112. * @return string
  113. */
  114. function logrep($object) {
  115. if (is_object($object)) {
  116. $class = get_class($object);
  117. if (isset($object->id)) {
  118. return "$class $object->id";
  119. }
  120. return $class;
  121. } elseif (is_string($object)) {
  122. $len = strlen($object);
  123. $fragment = mb_substr($object, 0, 32);
  124. if (mb_strlen($object) > 32) {
  125. $fragment .= '...';
  126. }
  127. return "string '$fragment' ($len bytes)";
  128. } elseif (is_array($object)) {
  129. return 'array with ' . count($object) .
  130. ' elements (keys:[' . implode(',', array_keys($object)) . '])';
  131. }
  132. return strval($object);
  133. }
  134. /**
  135. * Encode an object for queued storage.
  136. *
  137. * @param mixed $item
  138. * @return string
  139. */
  140. protected function encode($item): string
  141. {
  142. return serialize($item);
  143. }
  144. /**
  145. * Decode an object from queued storage.
  146. * Accepts notice reference entries and serialized items.
  147. *
  148. * @param string
  149. * @return mixed
  150. */
  151. protected function decode(string $frame)
  152. {
  153. $object = unserialize($frame);
  154. // If it is a string, we really store a JSON object in there
  155. // except if it begins with '<', because then it is XML.
  156. if (is_string($object) &&
  157. substr($object, 0, 1) != '<' &&
  158. !is_numeric($object))
  159. {
  160. $json = json_decode($object);
  161. if ($json === null) {
  162. throw new Exception('Bad frame in queue item');
  163. }
  164. // The JSON object has a type parameter which contains the class
  165. if (empty($json->type)) {
  166. throw new Exception('Type not specified for queue item');
  167. }
  168. if (!is_a($json->type, 'Managed_DataObject', true)) {
  169. throw new Exception('Managed_DataObject class does not exist for queue item');
  170. }
  171. // And each of these types should have a unique id (or uri)
  172. if (isset($json->id) && !empty($json->id)) {
  173. $object = call_user_func(array($json->type, 'getKV'), 'id', $json->id);
  174. } elseif (isset($json->uri) && !empty($json->uri)) {
  175. $object = call_user_func(array($json->type, 'getKV'), 'uri', $json->uri);
  176. }
  177. // But if no object was found, there's nothing we can handle
  178. if (!$object instanceof Managed_DataObject) {
  179. throw new Exception('Queue item frame referenced a non-existant object');
  180. }
  181. }
  182. // If the frame was not a string, it's either an array or an object.
  183. return $object;
  184. }
  185. /**
  186. * Instantiate the appropriate QueueHandler class for the given queue.
  187. *
  188. * @param string $queue
  189. * @return mixed QueueHandler or null
  190. */
  191. function getHandler($queue)
  192. {
  193. if (isset($this->handlers[$queue])) {
  194. $class = $this->handlers[$queue];
  195. if(is_object($class)) {
  196. return $class;
  197. } else if (class_exists($class)) {
  198. return new $class();
  199. } else {
  200. $this->_log(LOG_ERR, "Nonexistent handler class '$class' for queue '$queue'");
  201. }
  202. }
  203. throw new NoQueueHandlerException($queue);
  204. }
  205. /**
  206. * Get a list of registered queue transport names to be used
  207. * for listening in this daemon.
  208. *
  209. * @return array of strings
  210. */
  211. function activeQueues()
  212. {
  213. $queues = array();
  214. foreach ($this->activeGroups as $group) {
  215. if (isset($this->groups[$group])) {
  216. $queues = array_merge($queues, $this->groups[$group]);
  217. }
  218. }
  219. return array_keys($queues);
  220. }
  221. function getIgnoredTransports()
  222. {
  223. return array_keys($this->ignoredTransports);
  224. }
  225. function ignoreTransport($transport)
  226. {
  227. // key is used for uniqueness, value doesn't mean anything
  228. $this->ignoredTransports[$transport] = true;
  229. }
  230. /**
  231. * Initialize the list of queue handlers for the current site.
  232. *
  233. * @event StartInitializeQueueManager
  234. * @event EndInitializeQueueManager
  235. */
  236. function initialize()
  237. {
  238. $this->handlers = array();
  239. $this->groups = array();
  240. $this->groupsByTransport = array();
  241. if (Event::handle('StartInitializeQueueManager', array($this))) {
  242. $this->connect('distrib', 'DistribQueueHandler');
  243. $this->connect('ping', 'PingQueueHandler');
  244. if (common_config('sms', 'enabled')) {
  245. $this->connect('sms', 'SmsQueueHandler');
  246. }
  247. // Background user management tasks...
  248. $this->connect('deluser', 'DelUserQueueHandler');
  249. $this->connect('feedimp', 'FeedImporter');
  250. $this->connect('actimp', 'ActivityImporter');
  251. $this->connect('acctmove', 'AccountMover');
  252. $this->connect('actmove', 'ActivityMover');
  253. // For compat with old plugins not registering their own handlers.
  254. $this->connect('Module', 'ModuleQueueHandler');
  255. }
  256. Event::handle('EndInitializeQueueManager', array($this));
  257. }
  258. /**
  259. * Register a queue transport name and handler class for your plugin.
  260. * Only registered transports will be reliably picked up!
  261. *
  262. * @param string $transport
  263. * @param string $class class name or object instance
  264. * @param string $group
  265. */
  266. public function connect($transport, $class, $group='main')
  267. {
  268. $this->handlers[$transport] = $class;
  269. $this->groups[$group][$transport] = $class;
  270. $this->groupsByTransport[$transport] = $group;
  271. }
  272. /**
  273. * Set the active group which will be used for listening.
  274. * @param string $group
  275. */
  276. function setActiveGroup($group)
  277. {
  278. $this->activeGroups = array($group);
  279. }
  280. /**
  281. * Set the active group(s) which will be used for listening.
  282. * @param array $groups
  283. */
  284. function setActiveGroups($groups)
  285. {
  286. $this->activeGroups = $groups;
  287. }
  288. /**
  289. * @return string queue group for this queue
  290. */
  291. function queueGroup($queue)
  292. {
  293. if (isset($this->groupsByTransport[$queue])) {
  294. return $this->groupsByTransport[$queue];
  295. } else {
  296. throw new Exception("Requested group for unregistered transport $queue");
  297. }
  298. }
  299. /**
  300. * Send a statistic ping to the queue monitoring system,
  301. * optionally with a per-queue id.
  302. *
  303. * @param string $key
  304. * @param string $queue
  305. */
  306. function stats($key, $queue=false)
  307. {
  308. $owners = array();
  309. if ($queue) {
  310. $owners[] = "queue:$queue";
  311. $owners[] = "site:" . common_config('site', 'server');
  312. }
  313. if (isset($this->master)) {
  314. $this->master->stats($key, $owners);
  315. } else {
  316. $monitor = new QueueMonitor();
  317. $monitor->stats($key, $owners);
  318. }
  319. }
  320. protected function _log($level, $msg)
  321. {
  322. $class = get_class($this);
  323. if ($this->activeGroups) {
  324. $groups = ' (' . implode(',', $this->activeGroups) . ')';
  325. } else {
  326. $groups = '';
  327. }
  328. common_log($level, "$class$groups: $msg");
  329. }
  330. }