3 * StatusNet, the distributed open-source microblogging tool
5 * Abstract class for queue 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 * @copyright 2009 StatusNet, Inc.
27 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
28 * @link http://status.net/
31 require_once 'Stomp.php';
34 class StompQueueManager extends QueueManager
42 protected $sites = array();
44 function __construct()
46 parent::__construct();
47 $this->server = common_config('queue', 'stomp_server');
48 $this->username = common_config('queue', 'stomp_username');
49 $this->password = common_config('queue', 'stomp_password');
50 $this->base = common_config('queue', 'queue_basename');
54 * Tell the i/o master we only need a single instance to cover
55 * all sites running in this process.
57 public static function multiSite()
59 return IoManager::INSTANCE_PER_PROCESS;
63 * Record each site we'll be handling input for in this process,
64 * so we can listen to the necessary queues for it.
66 * @fixme possibly actually do subscription here to save another
67 * loop over all sites later?
68 * @fixme possibly don't assume it's the current site
70 public function addSite($server)
72 $this->sites[] = $server;
78 * Instantiate the appropriate QueueHandler class for the given queue.
80 * @param string $queue
81 * @return mixed QueueHandler or null
83 function getHandler($queue)
85 $handlers = $this->handlers[common_config('site', 'server')];
86 if (isset($handlers[$queue])) {
87 $class = $handlers[$queue];
88 if (class_exists($class)) {
91 common_log(LOG_ERR, "Nonexistent handler class '$class' for queue '$queue'");
94 common_log(LOG_ERR, "Requested handler for unkown queue '$queue'");
100 * Get a list of all registered queue transport names.
102 * @return array of strings
106 $group = $this->activeGroup();
107 $site = common_config('site', 'server');
108 if (empty($this->groups[$site][$group])) {
111 return array_keys($this->groups[$site][$group]);
116 * Register a queue transport name and handler class for your plugin.
117 * Only registered transports will be reliably picked up!
119 * @param string $transport
120 * @param string $class
121 * @param string $group
123 public function connect($transport, $class, $group='queuedaemon')
125 $this->handlers[common_config('site', 'server')][$transport] = $class;
126 $this->groups[common_config('site', 'server')][$group][$transport] = $class;
130 * Saves a notice object reference into the queue item table.
131 * @return boolean true on success
133 public function enqueue($object, $queue)
135 $msg = $this->encode($object);
136 $rep = $this->logrep($object);
140 // XXX: serialize and send entire notice
142 $result = $this->con->send($this->queueName($queue),
143 $msg, // BODY of the message
144 array ('created' => common_sql_now()));
147 common_log(LOG_ERR, "Error sending $rep to $queue queue");
151 common_log(LOG_DEBUG, "complete remote queueing $rep for $queue");
152 $this->stats('enqueued', $queue);
156 * Send any sockets we're listening on to the IO manager
159 * @return array of resources
161 public function getSockets()
163 return array($this->con->getSocket());
167 * We've got input to handle on our socket!
168 * Read any waiting Stomp frame(s) and process them.
170 * @param resource $socket
171 * @return boolean ok on success
173 public function handleInput($socket)
175 assert($socket === $this->con->getSocket());
177 $frames = $this->con->readFrames();
178 foreach ($frames as $frame) {
179 $ok = $ok && $this->_handleItem($frame);
185 * Initialize our connection and subscribe to all the queues
186 * we're going to need to handle...
188 * Side effects: in multi-site mode, may reset site configuration.
190 * @param IoMaster $master process/event controller
191 * @return bool return false on failure
193 public function start($master)
195 parent::start($master);
197 foreach ($this->sites as $server) {
198 StatusNet::init($server);
199 $this->doSubscribe();
202 $this->doSubscribe();
208 * Subscribe to all the queues we're going to need to handle...
210 * Side effects: in multi-site mode, may reset site configuration.
212 * @return bool return false on failure
214 public function finish()
217 foreach ($this->sites as $server) {
218 StatusNet::init($server);
219 $this->doUnsubscribe();
222 $this->doUnsubscribe();
228 * Lazy open connection to Stomp queue server.
230 protected function _connect()
232 if (empty($this->con)) {
233 $this->_log(LOG_INFO, "Connecting to '$this->server' as '$this->username'...");
234 $this->con = new LiberalStomp($this->server);
236 if ($this->con->connect($this->username, $this->password)) {
237 $this->_log(LOG_INFO, "Connected.");
239 $this->_log(LOG_ERR, 'Failed to connect to queue server');
240 throw new ServerException('Failed to connect to queue server');
246 * Subscribe to all enabled notice queues for the current site.
248 protected function doSubscribe()
251 foreach ($this->getQueues() as $queue) {
252 $rawqueue = $this->queueName($queue);
253 $this->_log(LOG_INFO, "Subscribing to $rawqueue");
254 $this->con->subscribe($rawqueue);
259 * Subscribe from all enabled notice queues for the current site.
261 protected function doUnsubscribe()
264 foreach ($this->getQueues() as $queue) {
265 $this->con->unsubscribe($this->queueName($queue));
270 * Handle and acknowledge an event that's come in through a queue.
272 * If the queue handler reports failure, the message is requeued for later.
273 * Missing notices or handler classes will drop the message.
275 * Side effects: in multi-site mode, may reset site configuration to
276 * match the site that queued the event.
278 * @param StompFrame $frame
281 protected function _handleItem($frame)
283 list($site, $queue) = $this->parseDestination($frame->headers['destination']);
284 if ($site != common_config('site', 'server')) {
285 $this->stats('switch');
286 StatusNet::init($site);
289 if (is_numeric($frame->body)) {
290 $id = intval($frame->body);
291 $info = "notice $id posted at {$frame->headers['created']} in queue $queue";
293 $notice = Notice::staticGet('id', $id);
294 if (empty($notice)) {
295 $this->_log(LOG_WARNING, "Skipping missing $info");
296 $this->con->ack($frame);
297 $this->stats('badnotice', $queue);
303 // @fixme should we serialize, or json, or what here?
304 $info = "string posted at {$frame->headers['created']} in queue $queue";
305 $item = $frame->body;
308 $handler = $this->getHandler($queue);
310 $this->_log(LOG_ERROR, "Missing handler class; skipping $info");
311 $this->con->ack($frame);
312 $this->stats('badhandler', $queue);
316 $ok = $handler->handle($item);
319 $this->_log(LOG_WARNING, "Failed handling $info");
320 // FIXME we probably shouldn't have to do
321 // this kind of queue management ourselves;
322 // if we don't ack, it should resend...
323 $this->con->ack($frame);
324 $this->enqueue($item, $queue);
325 $this->stats('requeued', $queue);
329 $this->_log(LOG_INFO, "Successfully handled $info");
330 $this->con->ack($frame);
331 $this->stats('handled', $queue);
336 * Combines the queue_basename from configuration with the
337 * site server name and queue name to give eg:
339 * /queue/statusnet/identi.ca/sms
341 * @param string $queue
344 protected function queueName($queue)
346 return common_config('queue', 'queue_basename') .
347 common_config('site', 'server') . '/' . $queue;
351 * Returns the site and queue name from the server-side queue.
353 * @param string queue destination (eg '/queue/statusnet/identi.ca/sms')
354 * @return array of site and queue: ('identi.ca','sms') or false if unrecognized
356 protected function parseDestination($dest)
358 $prefix = common_config('queue', 'queue_basename');
359 if (substr($dest, 0, strlen($prefix)) == $prefix) {
360 $rest = substr($dest, strlen($prefix));
361 return explode("/", $rest, 2);
363 common_log(LOG_ERR, "Got a message from unrecognized stomp queue: $dest");
364 return array(false, false);
368 function _log($level, $msg)
370 common_log($level, 'StompQueueManager: '.$msg);