queuemanager.php 11 KB

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