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';
32 require_once 'Stomp/Exception.php';
34 class StompQueueManager extends QueueManager
42 protected $useTransactions = true;
44 protected $sites = array();
45 protected $subscriptions = array();
47 protected $cons = array(); // all open connections
48 protected $disconnect = array();
49 protected $transaction = array();
50 protected $transactionCount = array();
51 protected $defaultIdx = 0;
53 function __construct()
55 parent::__construct();
56 $server = common_config('queue', 'stomp_server');
57 if (is_array($server)) {
58 $this->servers = $server;
60 $this->servers = array($server);
62 $this->username = common_config('queue', 'stomp_username');
63 $this->password = common_config('queue', 'stomp_password');
64 $this->base = common_config('queue', 'queue_basename');
65 $this->control = common_config('queue', 'control_channel');
69 * Tell the i/o master we only need a single instance to cover
70 * all sites running in this process.
72 public static function multiSite()
74 return IoManager::INSTANCE_PER_PROCESS;
78 * Record each site we'll be handling input for in this process,
79 * so we can listen to the necessary queues for it.
81 * @fixme possibly actually do subscription here to save another
82 * loop over all sites later?
83 * @fixme possibly don't assume it's the current site
85 public function addSite($server)
87 $this->sites[] = $server;
92 * Optional; ping any running queue handler daemons with a notification
93 * such as announcing a new site to handle or requesting clean shutdown.
94 * This avoids having to restart all the daemons manually to update configs
97 * Currently only relevant for multi-site queue managers such as Stomp.
99 * @param string $event event key
100 * @param string $param optional parameter to append to key
101 * @return boolean success
103 public function sendControlSignal($event, $param='')
107 $message .= ':' . $param;
110 $result = $this->_send($this->control,
112 array ('created' => common_sql_now()));
114 $this->_log(LOG_INFO, "Sent control ping to queue daemons: $message");
117 $this->_log(LOG_ERR, "Failed sending control ping to queue daemons: $message");
123 * Instantiate the appropriate QueueHandler class for the given queue.
125 * @param string $queue
126 * @return mixed QueueHandler or null
128 function getHandler($queue)
130 $handlers = $this->handlers[$this->currentSite()];
131 if (isset($handlers[$queue])) {
132 $class = $handlers[$queue];
133 if (class_exists($class)) {
136 common_log(LOG_ERR, "Nonexistent handler class '$class' for queue '$queue'");
139 common_log(LOG_ERR, "Requested handler for unkown queue '$queue'");
145 * Get a list of all registered queue transport names.
147 * @return array of strings
151 $group = $this->activeGroup();
152 $site = $this->currentSite();
153 if (empty($this->groups[$site][$group])) {
156 return array_keys($this->groups[$site][$group]);
161 * Register a queue transport name and handler class for your plugin.
162 * Only registered transports will be reliably picked up!
164 * @param string $transport
165 * @param string $class
166 * @param string $group
168 public function connect($transport, $class, $group='queuedaemon')
170 $this->handlers[$this->currentSite()][$transport] = $class;
171 $this->groups[$this->currentSite()][$group][$transport] = $class;
175 * Saves a notice object reference into the queue item table.
176 * @return boolean true on success
177 * @throws StompException on connection or send error
179 public function enqueue($object, $queue)
182 return $this->_doEnqueue($object, $queue, $this->defaultIdx);
186 * Saves a notice object reference into the queue item table
187 * on the given connection.
189 * @return boolean true on success
190 * @throws StompException on connection or send error
192 protected function _doEnqueue($object, $queue, $idx)
194 $msg = $this->encode($object);
195 $rep = $this->logrep($object);
197 $props = array('created' => common_sql_now());
198 if ($this->isPersistent($queue)) {
199 $props['persistent'] = 'true';
202 $con = $this->cons[$idx];
203 $host = $con->getServer();
204 $result = $con->send($this->queueName($queue), $msg, $props);
207 common_log(LOG_ERR, "Error sending $rep to $queue queue on $host");
211 common_log(LOG_DEBUG, "complete remote queueing $rep for $queue on $host");
212 $this->stats('enqueued', $queue);
217 * Determine whether messages to this queue should be marked as persistent.
218 * Actual persistent storage depends on the queue server's configuration.
219 * @param string $queue
222 protected function isPersistent($queue)
224 $mode = common_config('queue', 'stomp_persistent');
225 if (is_array($mode)) {
226 return in_array($queue, $mode);
233 * Send any sockets we're listening on to the IO manager
236 * @return array of resources
238 public function getSockets()
241 foreach ($this->cons as $con) {
243 $sockets[] = $con->getSocket();
250 * Get the Stomp connection object associated with the given socket.
251 * @param resource $socket
252 * @return int index into connections list
255 protected function connectionFromSocket($socket)
257 foreach ($this->cons as $i => $con) {
258 if ($con && $con->getSocket() === $socket) {
262 throw new Exception(__CLASS__ . " asked to read from unrecognized socket");
266 * We've got input to handle on our socket!
267 * Read any waiting Stomp frame(s) and process them.
269 * @param resource $socket
270 * @return boolean ok on success
272 public function handleInput($socket)
274 $idx = $this->connectionFromSocket($socket);
275 $con = $this->cons[$idx];
276 $host = $con->getServer();
280 $frames = $con->readFrames();
281 } catch (StompException $e) {
282 common_log(LOG_ERR, "Lost connection to $host: " . $e->getMessage());
283 $this->cons[$idx] = null;
284 $this->transaction[$idx] = null;
285 $this->disconnect[$idx] = time();
288 foreach ($frames as $frame) {
289 $dest = $frame->headers['destination'];
290 if ($dest == $this->control) {
291 if (!$this->handleControlSignal($idx, $frame)) {
292 // We got a control event that requests a shutdown;
293 // close out and stop handling anything else!
297 $ok = $ok && $this->handleItem($idx, $frame);
304 * Attempt to reconnect in background if we lost a connection.
309 foreach ($this->cons as $idx => $con) {
311 $age = $now - $this->disconnect[$idx];
313 $this->_reconnect($idx);
321 * Initialize our connection and subscribe to all the queues
322 * we're going to need to handle... If multiple queue servers
323 * are configured for failover, we'll listen to all of them.
325 * Side effects: in multi-site mode, may reset site configuration.
327 * @param IoMaster $master process/event controller
328 * @return bool return false on failure
330 public function start($master)
332 parent::start($master);
333 $this->_connectAll();
335 common_log(LOG_INFO, "Subscribing to $this->control");
336 foreach ($this->cons as $con) {
338 $con->subscribe($this->control);
342 foreach ($this->sites as $server) {
343 StatusNet::init($server);
344 $this->doSubscribe();
347 $this->doSubscribe();
349 foreach ($this->cons as $i => $con) {
358 * Subscribe to all the queues we're going to need to handle...
360 * Side effects: in multi-site mode, may reset site configuration.
362 * @return bool return false on failure
364 public function finish()
366 // If there are any outstanding delivered messages we haven't processed,
367 // free them for another thread to take.
368 foreach ($this->cons as $i => $con) {
371 $con->unsubscribe($this->control);
375 foreach ($this->sites as $server) {
376 StatusNet::init($server);
377 $this->doUnsubscribe();
380 $this->doUnsubscribe();
386 * Get identifier of the currently active site configuration
389 protected function currentSite()
391 return common_config('site', 'server'); // @fixme switch to nickname
395 * Lazy open a single connection to Stomp queue server.
396 * If multiple servers are configured, we let the Stomp client library
397 * worry about finding a working connection among them.
399 protected function _connect()
401 if (empty($this->cons)) {
402 $list = $this->servers;
403 if (count($list) > 1) {
404 shuffle($list); // Randomize to spread load
405 $url = 'failover://(' . implode(',', $list) . ')';
409 $con = $this->_doConnect($url);
410 $this->cons = array($con);
411 $this->transactionCount = array(0);
412 $this->transaction = array(null);
413 $this->disconnect = array(null);
418 * Lazy open connections to all Stomp servers, if in manual failover
419 * mode. This means the queue servers don't speak to each other, so
420 * we have to listen to all of them to make sure we get all events.
422 protected function _connectAll()
424 if (!common_config('queue', 'stomp_manual_failover')) {
425 return $this->_connect();
427 if (empty($this->cons)) {
428 $this->cons = array();
429 $this->transactionCount = array();
430 $this->transaction = array();
431 foreach ($this->servers as $idx => $server) {
433 $this->cons[] = $this->_doConnect($server);
434 $this->disconnect[] = null;
435 } catch (Exception $e) {
436 // s'okay, we'll live
437 $this->cons[] = null;
438 $this->disconnect[] = time();
440 $this->transactionCount[] = 0;
441 $this->transaction[] = null;
443 if (empty($this->cons)) {
444 throw new ServerException("No queue servers reachable...");
450 protected function _reconnect($idx)
453 $con = $this->_doConnect($this->servers[$idx]);
454 } catch (Exception $e) {
455 $this->_log(LOG_ERR, $e->getMessage());
459 $this->cons[$idx] = $con;
460 $this->disconnect[$idx] = null;
462 // now we have to listen to everything...
463 // @fixme refactor this nicer. :P
464 $host = $con->getServer();
465 $this->_log(LOG_INFO, "Resubscribing to $this->control on $host");
466 $con->subscribe($this->control);
467 foreach ($this->subscriptions as $site => $queues) {
468 foreach ($queues as $queue) {
469 $this->_log(LOG_INFO, "Resubscribing to $queue on $host");
470 $con->subscribe($queue);
475 // Try again later...
476 $this->disconnect[$idx] = time();
480 protected function _doConnect($server)
482 $this->_log(LOG_INFO, "Connecting to '$server' as '$this->username'...");
483 $con = new LiberalStomp($server);
485 if ($con->connect($this->username, $this->password)) {
486 $this->_log(LOG_INFO, "Connected.");
488 $this->_log(LOG_ERR, 'Failed to connect to queue server');
489 throw new ServerException('Failed to connect to queue server');
496 * Subscribe to all enabled notice queues for the current site.
498 protected function doSubscribe()
500 $site = $this->currentSite();
502 foreach ($this->getQueues() as $queue) {
503 $rawqueue = $this->queueName($queue);
504 $this->subscriptions[$site][$queue] = $rawqueue;
505 $this->_log(LOG_INFO, "Subscribing to $rawqueue");
506 foreach ($this->cons as $con) {
508 $con->subscribe($rawqueue);
515 * Subscribe from all enabled notice queues for the current site.
517 protected function doUnsubscribe()
519 $site = $this->currentSite();
521 if (!empty($this->subscriptions[$site])) {
522 foreach ($this->subscriptions[$site] as $queue => $rawqueue) {
523 $this->_log(LOG_INFO, "Unsubscribing from $rawqueue");
524 foreach ($this->cons as $con) {
526 $con->unsubscribe($rawqueue);
529 unset($this->subscriptions[$site][$queue]);
535 * Handle and acknowledge an event that's come in through a queue.
537 * If the queue handler reports failure, the message is requeued for later.
538 * Missing notices or handler classes will drop the message.
540 * Side effects: in multi-site mode, may reset site configuration to
541 * match the site that queued the event.
543 * @param int $idx connection index
544 * @param StompFrame $frame
547 protected function handleItem($idx, $frame)
549 $this->defaultIdx = $idx;
551 list($site, $queue) = $this->parseDestination($frame->headers['destination']);
552 if ($site != $this->currentSite()) {
553 $this->stats('switch');
554 StatusNet::init($site);
557 $host = $this->cons[$idx]->getServer();
558 if (is_numeric($frame->body)) {
559 $id = intval($frame->body);
560 $info = "notice $id posted at {$frame->headers['created']} in queue $queue from $host";
562 $notice = Notice::staticGet('id', $id);
563 if (empty($notice)) {
564 $this->_log(LOG_WARNING, "Skipping missing $info");
565 $this->ack($idx, $frame);
568 $this->stats('badnotice', $queue);
574 // @fixme should we serialize, or json, or what here?
575 $info = "string posted at {$frame->headers['created']} in queue $queue from $host";
576 $item = $frame->body;
579 $handler = $this->getHandler($queue);
581 $this->_log(LOG_ERR, "Missing handler class; skipping $info");
582 $this->ack($idx, $frame);
585 $this->stats('badhandler', $queue);
589 // If there's an exception when handling,
590 // log the error and let it get requeued.
593 $ok = $handler->handle($item);
594 } catch (Exception $e) {
595 $this->_log(LOG_ERR, "Exception on queue $queue: " . $e->getMessage());
600 $this->_log(LOG_WARNING, "Failed handling $info");
601 // FIXME we probably shouldn't have to do
602 // this kind of queue management ourselves;
603 // if we don't ack, it should resend...
604 $this->ack($idx, $frame);
605 $this->enqueue($item, $queue);
608 $this->stats('requeued', $queue);
612 $this->_log(LOG_INFO, "Successfully handled $info");
613 $this->ack($idx, $frame);
616 $this->stats('handled', $queue);
621 * Process a control signal broadcast.
623 * @param int $idx connection index
624 * @param array $frame Stomp frame
625 * @return bool true to continue; false to stop further processing.
627 protected function handleControlSignal($idx, $frame)
629 $message = trim($frame->body);
630 if (strpos($message, ':') !== false) {
631 list($event, $param) = explode(':', $message, 2);
639 if ($event == 'shutdown') {
640 $this->master->requestShutdown();
642 } else if ($event == 'restart') {
643 $this->master->requestRestart();
645 } else if ($event == 'update') {
646 $this->updateSiteConfig($param);
648 $this->_log(LOG_ERR, "Ignoring unrecognized control message: $message");
651 $this->ack($idx, $frame);
658 * Set us up with queue subscriptions for a new site added at runtime,
659 * triggered by a broadcast to the 'statusnet-control' topic.
661 * @param array $frame Stomp frame
662 * @return bool true to continue; false to stop further processing.
664 protected function updateSiteConfig($nickname)
666 if (empty($this->sites)) {
667 if ($nickname == common_config('site', 'nickname')) {
668 StatusNet::init(common_config('site', 'server'));
669 $this->doUnsubscribe();
670 $this->doSubscribe();
672 $this->_log(LOG_INFO, "Ignoring update ping for other site $nickname");
675 $sn = Status_network::staticGet($nickname);
677 $server = $sn->getServerName(); // @fixme do config-by-nick
678 StatusNet::init($server);
679 if (empty($this->sites[$server])) {
680 $this->addSite($server);
682 $this->_log(LOG_INFO, "(Re)subscribing to queues for site $nickname / $server");
683 $this->doUnsubscribe();
684 $this->doSubscribe();
685 $this->stats('siteupdate');
687 $this->_log(LOG_ERR, "Ignoring ping for unrecognized new site $nickname");
693 * Combines the queue_basename from configuration with the
694 * site server name and queue name to give eg:
696 * /queue/statusnet/identi.ca/sms
698 * @param string $queue
701 protected function queueName($queue)
703 return common_config('queue', 'queue_basename') .
704 $this->currentSite() . '/' . $queue;
708 * Returns the site and queue name from the server-side queue.
710 * @param string queue destination (eg '/queue/statusnet/identi.ca/sms')
711 * @return array of site and queue: ('identi.ca','sms') or false if unrecognized
713 protected function parseDestination($dest)
715 $prefix = common_config('queue', 'queue_basename');
716 if (substr($dest, 0, strlen($prefix)) == $prefix) {
717 $rest = substr($dest, strlen($prefix));
718 return explode("/", $rest, 2);
720 common_log(LOG_ERR, "Got a message from unrecognized stomp queue: $dest");
721 return array(false, false);
725 function _log($level, $msg)
727 common_log($level, 'StompQueueManager: '.$msg);
730 protected function begin($idx)
732 if ($this->useTransactions) {
733 if (!empty($this->transaction[$idx])) {
734 throw new Exception("Tried to start transaction in the middle of a transaction");
736 $this->transactionCount[$idx]++;
737 $this->transaction[$idx] = $this->master->id . '-' . $this->transactionCount[$idx] . '-' . time();
738 $this->cons[$idx]->begin($this->transaction[$idx]);
742 protected function ack($idx, $frame)
744 if ($this->useTransactions) {
745 if (empty($this->transaction[$idx])) {
746 throw new Exception("Tried to ack but not in a transaction");
748 $this->cons[$idx]->ack($frame, $this->transaction[$idx]);
750 $this->cons[$idx]->ack($frame);
754 protected function commit($idx)
756 if ($this->useTransactions) {
757 if (empty($this->transaction[$idx])) {
758 throw new Exception("Tried to commit but not in a transaction");
760 $this->cons[$idx]->commit($this->transaction[$idx]);
761 $this->transaction[$idx] = null;
765 protected function rollback($idx)
767 if ($this->useTransactions) {
768 if (empty($this->transaction[$idx])) {
769 throw new Exception("Tried to rollback but not in a transaction");
771 $this->cons[$idx]->commit($this->transaction[$idx]);
772 $this->transaction[$idx] = null;