3 * StatusNet, the distributed open-source microblogging tool
5 * Abstract class for i/o managers
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.
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.
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/>.
22 * @category QueueManager
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/
33 * Completed child classes must implement the enqueue() method.
35 * For background processing, classes should implement either socket-based
36 * input (handleInput(), getSockets()) or idle-loop polling (idle()).
38 abstract class QueueManager extends IoManager
42 protected $master = null;
43 protected $handlers = array();
44 protected $groups = array();
45 protected $activeGroups = array();
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.
52 * Plugins can add to the built-in types by hooking StartNewQueueManager.
54 * @return QueueManager
56 public static function get()
58 if (empty(self::$qm)) {
60 if (Event::handle('StartNewQueueManager', array(&self::$qm))) {
62 $enabled = common_config('queue', 'enabled');
63 $type = common_config('queue', 'subsystem');
66 // does everything immediately
67 self::$qm = new UnQueueManager();
71 self::$qm = new DBQueueManager();
74 self::$qm = new StompQueueManager();
77 throw new ServerException("No queue manager class for type '$type'");
87 * @fixme wouldn't necessarily work with other class types.
88 * Better to change the interface...?
90 public static function multiSite()
92 if (common_config('queue', 'subsystem') == 'stomp') {
93 return IoManager::INSTANCE_PER_PROCESS;
95 return IoManager::SINGLE_ONLY;
99 function __construct()
105 * Optional; ping any running queue handler daemons with a notification
106 * such as announcing a new site to handle or requesting clean shutdown.
107 * This avoids having to restart all the daemons manually to update configs
110 * Called from scripts/queuectl.php controller utility.
112 * @param string $event event key
113 * @param string $param optional parameter to append to key
114 * @return boolean success
116 public function sendControlSignal($event, $param='')
118 throw new Exception(get_class($this) . " does not support control signals.");
122 * Store an object (usually/always a Notice) into the given queue
123 * for later processing. No guarantee is made on when it will be
124 * processed; it could be immediately or at some unspecified point
127 * Must be implemented by any queue manager.
129 * @param Notice $object
130 * @param string $queue
132 abstract function enqueue($object, $queue);
135 * Build a representation for an object for logging
139 function logrep($object) {
140 if (is_object($object)) {
141 $class = get_class($object);
142 if (isset($object->id)) {
143 return "$class $object->id";
146 } elseif (is_string($object)) {
147 $len = strlen($object);
148 $fragment = mb_substr($object, 0, 32);
149 if (mb_strlen($object) > 32) {
152 return "string '$fragment' ($len bytes)";
153 } elseif (is_array($object)) {
154 return 'array with ' . count($object) .
155 ' elements (keys:[' . implode(',', array_keys($object)) . '])';
157 return strval($object);
161 * Encode an object for queued storage.
166 protected function encode($item)
168 return serialize($item);
172 * Decode an object from queued storage.
173 * Accepts notice reference entries and serialized items.
178 protected function decode($frame)
180 $object = unserialize($frame);
182 // If it is a string, we really store a JSON object in there
183 // except if it begins with '<', because then it is XML.
184 if (is_string($object) &&
185 substr($object, 0, 1) != '<' &&
186 !is_numeric($object))
188 $json = json_decode($object);
189 if ($json === null) {
190 throw new Exception('Bad frame in queue item');
193 // The JSON object has a type parameter which contains the class
194 if (empty($json->type)) {
195 throw new Exception('Type not specified for queue item');
197 if (!is_a($json->type, 'Managed_DataObject', true)) {
198 throw new Exception('Managed_DataObject class does not exist for queue item');
201 // And each of these types should have a unique id (or uri)
202 if (isset($json->id) && !empty($json->id)) {
203 $object = call_user_func(array($json->type, 'getKV'), 'id', $json->id);
204 } elseif (isset($json->uri) && !empty($json->uri)) {
205 $object = call_user_func(array($json->type, 'getKV'), 'uri', $json->uri);
208 // But if no object was found, there's nothing we can handle
209 if (!$object instanceof Managed_DataObject) {
210 throw new Exception('Queue item frame referenced a non-existant object');
214 // If the frame was not a string, it's either an array or an object.
220 * Instantiate the appropriate QueueHandler class for the given queue.
222 * @param string $queue
223 * @return mixed QueueHandler or null
225 function getHandler($queue)
227 if (isset($this->handlers[$queue])) {
228 $class = $this->handlers[$queue];
229 if(is_object($class)) {
231 } else if (class_exists($class)) {
234 $this->_log(LOG_ERR, "Nonexistent handler class '$class' for queue '$queue'");
237 $this->_log(LOG_ERR, "Requested handler for unkown queue '$queue'");
243 * Get a list of registered queue transport names to be used
244 * for listening in this daemon.
246 * @return array of strings
248 function activeQueues()
251 foreach ($this->activeGroups as $group) {
252 if (isset($this->groups[$group])) {
253 $queues = array_merge($queues, $this->groups[$group]);
257 return array_keys($queues);
261 * Initialize the list of queue handlers for the current site.
263 * @event StartInitializeQueueManager
264 * @event EndInitializeQueueManager
266 function initialize()
268 $this->handlers = array();
269 $this->groups = array();
270 $this->groupsByTransport = array();
272 if (Event::handle('StartInitializeQueueManager', array($this))) {
273 $this->connect('distrib', 'DistribQueueHandler');
274 $this->connect('ping', 'PingQueueHandler');
275 if (common_config('sms', 'enabled')) {
276 $this->connect('sms', 'SmsQueueHandler');
279 // Background user management tasks...
280 $this->connect('deluser', 'DelUserQueueHandler');
281 $this->connect('feedimp', 'FeedImporter');
282 $this->connect('actimp', 'ActivityImporter');
283 $this->connect('acctmove', 'AccountMover');
284 $this->connect('actmove', 'ActivityMover');
286 // For compat with old plugins not registering their own handlers.
287 $this->connect('plugin', 'PluginQueueHandler');
289 Event::handle('EndInitializeQueueManager', array($this));
293 * Register a queue transport name and handler class for your plugin.
294 * Only registered transports will be reliably picked up!
296 * @param string $transport
297 * @param string $class class name or object instance
298 * @param string $group
300 public function connect($transport, $class, $group='main')
302 $this->handlers[$transport] = $class;
303 $this->groups[$group][$transport] = $class;
304 $this->groupsByTransport[$transport] = $group;
308 * Set the active group which will be used for listening.
309 * @param string $group
311 function setActiveGroup($group)
313 $this->activeGroups = array($group);
317 * Set the active group(s) which will be used for listening.
318 * @param array $groups
320 function setActiveGroups($groups)
322 $this->activeGroups = $groups;
326 * @return string queue group for this queue
328 function queueGroup($queue)
330 if (isset($this->groupsByTransport[$queue])) {
331 return $this->groupsByTransport[$queue];
333 throw new Exception("Requested group for unregistered transport $queue");
338 * Send a statistic ping to the queue monitoring system,
339 * optionally with a per-queue id.
342 * @param string $queue
344 function stats($key, $queue=false)
348 $owners[] = "queue:$queue";
349 $owners[] = "site:" . common_config('site', 'server');
351 if (isset($this->master)) {
352 $this->master->stats($key, $owners);
354 $monitor = new QueueMonitor();
355 $monitor->stats($key, $owners);
359 protected function _log($level, $msg)
361 $class = get_class($this);
362 if ($this->activeGroups) {
363 $groups = ' (' . implode(',', $this->activeGroups) . ')';
367 common_log($level, "$class$groups: $msg");