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
43 protected $sites = array();
44 protected $subscriptions = array();
46 protected $useTransactions = true;
47 protected $transaction = null;
48 protected $transactionCount = 0;
50 function __construct()
52 parent::__construct();
53 $this->server = common_config('queue', 'stomp_server');
54 $this->username = common_config('queue', 'stomp_username');
55 $this->password = common_config('queue', 'stomp_password');
56 $this->base = common_config('queue', 'queue_basename');
57 $this->control = common_config('queue', 'control_channel');
61 * Tell the i/o master we only need a single instance to cover
62 * all sites running in this process.
64 public static function multiSite()
66 return IoManager::INSTANCE_PER_PROCESS;
70 * Record each site we'll be handling input for in this process,
71 * so we can listen to the necessary queues for it.
73 * @fixme possibly actually do subscription here to save another
74 * loop over all sites later?
75 * @fixme possibly don't assume it's the current site
77 public function addSite($server)
79 $this->sites[] = $server;
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
89 * Currently only relevant for multi-site queue managers such as Stomp.
91 * @param string $event event key
92 * @param string $param optional parameter to append to key
93 * @return boolean success
95 public function sendControlSignal($event, $param='')
99 $message .= ':' . $param;
102 $result = $this->con->send($this->control,
104 array ('created' => common_sql_now()));
106 $this->_log(LOG_INFO, "Sent control ping to queue daemons: $message");
109 $this->_log(LOG_ERR, "Failed sending control ping to queue daemons: $message");
115 * Instantiate the appropriate QueueHandler class for the given queue.
117 * @param string $queue
118 * @return mixed QueueHandler or null
120 function getHandler($queue)
122 $handlers = $this->handlers[$this->currentSite()];
123 if (isset($handlers[$queue])) {
124 $class = $handlers[$queue];
125 if (class_exists($class)) {
128 common_log(LOG_ERR, "Nonexistent handler class '$class' for queue '$queue'");
131 common_log(LOG_ERR, "Requested handler for unkown queue '$queue'");
137 * Get a list of all registered queue transport names.
139 * @return array of strings
143 $group = $this->activeGroup();
144 $site = $this->currentSite();
145 if (empty($this->groups[$site][$group])) {
148 return array_keys($this->groups[$site][$group]);
153 * Register a queue transport name and handler class for your plugin.
154 * Only registered transports will be reliably picked up!
156 * @param string $transport
157 * @param string $class
158 * @param string $group
160 public function connect($transport, $class, $group='queuedaemon')
162 $this->handlers[$this->currentSite()][$transport] = $class;
163 $this->groups[$this->currentSite()][$group][$transport] = $class;
167 * Saves a notice object reference into the queue item table.
168 * @return boolean true on success
170 public function enqueue($object, $queue)
172 $msg = $this->encode($object);
173 $rep = $this->logrep($object);
177 // XXX: serialize and send entire notice
179 $result = $this->con->send($this->queueName($queue),
180 $msg, // BODY of the message
181 array ('created' => common_sql_now(),
182 'persistent' => 'true'));
185 common_log(LOG_ERR, "Error sending $rep to $queue queue");
189 common_log(LOG_DEBUG, "complete remote queueing $rep for $queue");
190 $this->stats('enqueued', $queue);
194 * Send any sockets we're listening on to the IO manager
197 * @return array of resources
199 public function getSockets()
201 return array($this->con->getSocket());
205 * We've got input to handle on our socket!
206 * Read any waiting Stomp frame(s) and process them.
208 * @param resource $socket
209 * @return boolean ok on success
211 public function handleInput($socket)
213 assert($socket === $this->con->getSocket());
215 $frames = $this->con->readFrames();
216 foreach ($frames as $frame) {
217 $dest = $frame->headers['destination'];
218 if ($dest == $this->control) {
219 if (!$this->handleControlSignal($frame)) {
220 // We got a control event that requests a shutdown;
221 // close out and stop handling anything else!
225 $ok = $ok && $this->handleItem($frame);
232 * Initialize our connection and subscribe to all the queues
233 * we're going to need to handle...
235 * Side effects: in multi-site mode, may reset site configuration.
237 * @param IoMaster $master process/event controller
238 * @return bool return false on failure
240 public function start($master)
242 parent::start($master);
245 common_log(LOG_INFO, "Subscribing to $this->control");
246 $this->con->subscribe($this->control);
248 foreach ($this->sites as $server) {
249 StatusNet::init($server);
250 $this->doSubscribe();
253 $this->doSubscribe();
260 * Subscribe to all the queues we're going to need to handle...
262 * Side effects: in multi-site mode, may reset site configuration.
264 * @return bool return false on failure
266 public function finish()
268 // If there are any outstanding delivered messages we haven't processed,
269 // free them for another thread to take.
271 $this->con->unsubscribe($this->control);
273 foreach ($this->sites as $server) {
274 StatusNet::init($server);
275 $this->doUnsubscribe();
278 $this->doUnsubscribe();
284 * Get identifier of the currently active site configuration
287 protected function currentSite()
289 return common_config('site', 'server'); // @fixme switch to nickname
293 * Lazy open connection to Stomp queue server.
295 protected function _connect()
297 if (empty($this->con)) {
298 $this->_log(LOG_INFO, "Connecting to '$this->server' as '$this->username'...");
299 $this->con = new LiberalStomp($this->server);
301 if ($this->con->connect($this->username, $this->password)) {
302 $this->_log(LOG_INFO, "Connected.");
304 $this->_log(LOG_ERR, 'Failed to connect to queue server');
305 throw new ServerException('Failed to connect to queue server');
311 * Subscribe to all enabled notice queues for the current site.
313 protected function doSubscribe()
315 $site = $this->currentSite();
317 foreach ($this->getQueues() as $queue) {
318 $rawqueue = $this->queueName($queue);
319 $this->subscriptions[$site][$queue] = $rawqueue;
320 $this->_log(LOG_INFO, "Subscribing to $rawqueue");
321 $this->con->subscribe($rawqueue);
326 * Subscribe from all enabled notice queues for the current site.
328 protected function doUnsubscribe()
330 $site = $this->currentSite();
332 if (!empty($this->subscriptions[$site])) {
333 foreach ($this->subscriptions[$site] as $queue => $rawqueue) {
334 $this->_log(LOG_INFO, "Unsubscribing from $rawqueue");
335 $this->con->unsubscribe($rawqueue);
336 unset($this->subscriptions[$site][$queue]);
342 * Handle and acknowledge an event that's come in through a queue.
344 * If the queue handler reports failure, the message is requeued for later.
345 * Missing notices or handler classes will drop the message.
347 * Side effects: in multi-site mode, may reset site configuration to
348 * match the site that queued the event.
350 * @param StompFrame $frame
353 protected function handleItem($frame)
355 list($site, $queue) = $this->parseDestination($frame->headers['destination']);
356 if ($site != $this->currentSite()) {
357 $this->stats('switch');
358 StatusNet::init($site);
361 if (is_numeric($frame->body)) {
362 $id = intval($frame->body);
363 $info = "notice $id posted at {$frame->headers['created']} in queue $queue";
365 $notice = Notice::staticGet('id', $id);
366 if (empty($notice)) {
367 $this->_log(LOG_WARNING, "Skipping missing $info");
371 $this->stats('badnotice', $queue);
377 // @fixme should we serialize, or json, or what here?
378 $info = "string posted at {$frame->headers['created']} in queue $queue";
379 $item = $frame->body;
382 $handler = $this->getHandler($queue);
384 $this->_log(LOG_ERR, "Missing handler class; skipping $info");
388 $this->stats('badhandler', $queue);
392 $ok = $handler->handle($item);
395 $this->_log(LOG_WARNING, "Failed handling $info");
396 // FIXME we probably shouldn't have to do
397 // this kind of queue management ourselves;
398 // if we don't ack, it should resend...
400 $this->enqueue($item, $queue);
403 $this->stats('requeued', $queue);
407 $this->_log(LOG_INFO, "Successfully handled $info");
411 $this->stats('handled', $queue);
416 * Process a control signal broadcast.
418 * @param array $frame Stomp frame
419 * @return bool true to continue; false to stop further processing.
421 protected function handleControlSignal($frame)
423 $message = trim($frame->body);
424 if (strpos($message, ':') !== false) {
425 list($event, $param) = explode(':', $message, 2);
433 if ($event == 'shutdown') {
434 $this->master->requestShutdown();
436 } else if ($event == 'restart') {
437 $this->master->requestRestart();
439 } else if ($event == 'update') {
440 $this->updateSiteConfig($param);
442 $this->_log(LOG_ERR, "Ignoring unrecognized control message: $message");
452 * Set us up with queue subscriptions for a new site added at runtime,
453 * triggered by a broadcast to the 'statusnet-control' topic.
455 * @param array $frame Stomp frame
456 * @return bool true to continue; false to stop further processing.
458 protected function updateSiteConfig($nickname)
460 if (empty($this->sites)) {
461 if ($nickname == common_config('site', 'nickname')) {
462 StatusNet::init(common_config('site', 'server'));
463 $this->doUnsubscribe();
464 $this->doSubscribe();
466 $this->_log(LOG_INFO, "Ignoring update ping for other site $nickname");
469 $sn = Status_network::staticGet($nickname);
471 $server = $sn->getServerName(); // @fixme do config-by-nick
472 StatusNet::init($server);
473 if (empty($this->sites[$server])) {
474 $this->addSite($server);
476 $this->_log(LOG_INFO, "(Re)subscribing to queues for site $nickname / $server");
477 $this->doUnsubscribe();
478 $this->doSubscribe();
479 $this->stats('siteupdate');
481 $this->_log(LOG_ERR, "Ignoring ping for unrecognized new site $nickname");
487 * Combines the queue_basename from configuration with the
488 * site server name and queue name to give eg:
490 * /queue/statusnet/identi.ca/sms
492 * @param string $queue
495 protected function queueName($queue)
497 return common_config('queue', 'queue_basename') .
498 $this->currentSite() . '/' . $queue;
502 * Returns the site and queue name from the server-side queue.
504 * @param string queue destination (eg '/queue/statusnet/identi.ca/sms')
505 * @return array of site and queue: ('identi.ca','sms') or false if unrecognized
507 protected function parseDestination($dest)
509 $prefix = common_config('queue', 'queue_basename');
510 if (substr($dest, 0, strlen($prefix)) == $prefix) {
511 $rest = substr($dest, strlen($prefix));
512 return explode("/", $rest, 2);
514 common_log(LOG_ERR, "Got a message from unrecognized stomp queue: $dest");
515 return array(false, false);
519 function _log($level, $msg)
521 common_log($level, 'StompQueueManager: '.$msg);
524 protected function begin()
526 if ($this->useTransactions) {
527 if ($this->transaction) {
528 throw new Exception("Tried to start transaction in the middle of a transaction");
530 $this->transactionCount++;
531 $this->transaction = $this->master->id . '-' . $this->transactionCount . '-' . time();
532 $this->con->begin($this->transaction);
536 protected function ack($frame)
538 if ($this->useTransactions) {
539 if (!$this->transaction) {
540 throw new Exception("Tried to ack but not in a transaction");
543 $this->con->ack($frame, $this->transaction);
546 protected function commit()
548 if ($this->useTransactions) {
549 if (!$this->transaction) {
550 throw new Exception("Tried to commit but not in a transaction");
552 $this->con->commit($this->transaction);
553 $this->transaction = null;
557 protected function rollback()
559 if ($this->useTransactions) {
560 if (!$this->transaction) {
561 throw new Exception("Tried to rollback but not in a transaction");
563 $this->con->commit($this->transaction);
564 $this->transaction = null;