queuemanager.php 11 KB

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