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 $con = $this->cons[$this->defaultIdx];
111 $result = $con->send($this->control,
113 array ('created' => common_sql_now()));
115 $this->_log(LOG_INFO, "Sent control ping to queue daemons: $message");
118 $this->_log(LOG_ERR, "Failed sending control ping to queue daemons: $message");
124 * Instantiate the appropriate QueueHandler class for the given queue.
126 * @param string $queue
127 * @return mixed QueueHandler or null
129 function getHandler($queue)
131 $handlers = $this->handlers[$this->currentSite()];
132 if (isset($handlers[$queue])) {
133 $class = $handlers[$queue];
134 if (class_exists($class)) {
137 common_log(LOG_ERR, "Nonexistent handler class '$class' for queue '$queue'");
140 common_log(LOG_ERR, "Requested handler for unkown queue '$queue'");
146 * Get a list of all registered queue transport names.
148 * @return array of strings
152 $group = $this->activeGroup();
153 $site = $this->currentSite();
154 if (empty($this->groups[$site][$group])) {
157 return array_keys($this->groups[$site][$group]);
162 * Register a queue transport name and handler class for your plugin.
163 * Only registered transports will be reliably picked up!
165 * @param string $transport
166 * @param string $class
167 * @param string $group
169 public function connect($transport, $class, $group='queuedaemon')
171 $this->handlers[$this->currentSite()][$transport] = $class;
172 $this->groups[$this->currentSite()][$group][$transport] = $class;
176 * Saves a notice object reference into the queue item table.
177 * @return boolean true on success
178 * @throws StompException on connection or send error
180 public function enqueue($object, $queue)
183 return $this->_doEnqueue($object, $queue, $this->defaultIdx);
187 * Saves a notice object reference into the queue item table
188 * on the given connection.
190 * @return boolean true on success
191 * @throws StompException on connection or send error
193 protected function _doEnqueue($object, $queue, $idx)
195 $msg = $this->encode($object);
196 $rep = $this->logrep($object);
198 $props = array('created' => common_sql_now());
199 if ($this->isPersistent($queue)) {
200 $props['persistent'] = 'true';
203 $con = $this->cons[$idx];
204 $host = $con->getServer();
205 $result = $con->send($this->queueName($queue), $msg, $props);
208 common_log(LOG_ERR, "Error sending $rep to $queue queue on $host");
212 common_log(LOG_DEBUG, "complete remote queueing $rep for $queue on $host");
213 $this->stats('enqueued', $queue);
218 * Determine whether messages to this queue should be marked as persistent.
219 * Actual persistent storage depends on the queue server's configuration.
220 * @param string $queue
223 protected function isPersistent($queue)
225 $mode = common_config('queue', 'stomp_persistent');
226 if (is_array($mode)) {
227 return in_array($queue, $mode);
234 * Send any sockets we're listening on to the IO manager
237 * @return array of resources
239 public function getSockets()
242 foreach ($this->cons as $con) {
244 $sockets[] = $con->getSocket();
251 * Get the Stomp connection object associated with the given socket.
252 * @param resource $socket
253 * @return int index into connections list
256 protected function connectionFromSocket($socket)
258 foreach ($this->cons as $i => $con) {
259 if ($con && $con->getSocket() === $socket) {
263 throw new Exception(__CLASS__ . " asked to read from unrecognized socket");
267 * We've got input to handle on our socket!
268 * Read any waiting Stomp frame(s) and process them.
270 * @param resource $socket
271 * @return boolean ok on success
273 public function handleInput($socket)
275 $idx = $this->connectionFromSocket($socket);
276 $con = $this->cons[$idx];
277 $host = $con->getServer();
281 $frames = $con->readFrames();
282 } catch (StompException $e) {
283 common_log(LOG_ERR, "Lost connection to $host: " . $e->getMessage());
284 $this->cons[$idx] = null;
285 $this->transaction[$idx] = null;
286 $this->disconnect[$idx] = time();
289 foreach ($frames as $frame) {
290 $dest = $frame->headers['destination'];
291 if ($dest == $this->control) {
292 if (!$this->handleControlSignal($idx, $frame)) {
293 // We got a control event that requests a shutdown;
294 // close out and stop handling anything else!
298 $ok = $ok && $this->handleItem($idx, $frame);
305 * Attempt to reconnect in background if we lost a connection.
310 foreach ($this->cons as $idx => $con) {
312 $age = $now - $this->disconnect[$idx];
314 $this->_reconnect($idx);
322 * Initialize our connection and subscribe to all the queues
323 * we're going to need to handle... If multiple queue servers
324 * are configured for failover, we'll listen to all of them.
326 * Side effects: in multi-site mode, may reset site configuration.
328 * @param IoMaster $master process/event controller
329 * @return bool return false on failure
331 public function start($master)
333 parent::start($master);
334 $this->_connectAll();
336 common_log(LOG_INFO, "Subscribing to $this->control");
337 foreach ($this->cons as $con) {
339 $con->subscribe($this->control);
343 foreach ($this->sites as $server) {
344 StatusNet::init($server);
345 $this->doSubscribe();
348 $this->doSubscribe();
350 foreach ($this->cons as $i => $con) {
359 * Subscribe to all the queues we're going to need to handle...
361 * Side effects: in multi-site mode, may reset site configuration.
363 * @return bool return false on failure
365 public function finish()
367 // If there are any outstanding delivered messages we haven't processed,
368 // free them for another thread to take.
369 foreach ($this->cons as $i => $con) {
373 $this->cons[$i] = null;
380 * Get identifier of the currently active site configuration
383 protected function currentSite()
385 return common_config('site', 'server'); // @fixme switch to nickname
389 * Lazy open a single connection to Stomp queue server.
390 * If multiple servers are configured, we let the Stomp client library
391 * worry about finding a working connection among them.
393 protected function _connect()
395 if (empty($this->cons)) {
396 $list = $this->servers;
397 if (count($list) > 1) {
398 shuffle($list); // Randomize to spread load
399 $url = 'failover://(' . implode(',', $list) . ')';
403 $con = $this->_doConnect($url);
404 $this->cons = array($con);
405 $this->transactionCount = array(0);
406 $this->transaction = array(null);
407 $this->disconnect = array(null);
412 * Lazy open connections to all Stomp servers, if in manual failover
413 * mode. This means the queue servers don't speak to each other, so
414 * we have to listen to all of them to make sure we get all events.
416 protected function _connectAll()
418 if (!common_config('queue', 'stomp_manual_failover')) {
419 return $this->_connect();
421 if (empty($this->cons)) {
422 $this->cons = array();
423 $this->transactionCount = array();
424 $this->transaction = array();
425 foreach ($this->servers as $idx => $server) {
427 $this->cons[] = $this->_doConnect($server);
428 $this->disconnect[] = null;
429 } catch (Exception $e) {
430 // s'okay, we'll live
431 $this->cons[] = null;
432 $this->disconnect[] = time();
434 $this->transactionCount[] = 0;
435 $this->transaction[] = null;
437 if (empty($this->cons)) {
438 throw new ServerException("No queue servers reachable...");
444 protected function _reconnect($idx)
447 $con = $this->_doConnect($this->servers[$idx]);
448 } catch (Exception $e) {
449 $this->_log(LOG_ERR, $e->getMessage());
453 $this->cons[$idx] = $con;
454 $this->disconnect[$idx] = null;
456 // now we have to listen to everything...
457 // @fixme refactor this nicer. :P
458 $host = $con->getServer();
459 $this->_log(LOG_INFO, "Resubscribing to $this->control on $host");
460 $con->subscribe($this->control);
461 foreach ($this->subscriptions as $site => $queues) {
462 foreach ($queues as $queue) {
463 $this->_log(LOG_INFO, "Resubscribing to $queue on $host");
464 $con->subscribe($queue);
469 // Try again later...
470 $this->disconnect[$idx] = time();
474 protected function _doConnect($server)
476 $this->_log(LOG_INFO, "Connecting to '$server' as '$this->username'...");
477 $con = new LiberalStomp($server);
479 if ($con->connect($this->username, $this->password)) {
480 $this->_log(LOG_INFO, "Connected.");
482 $this->_log(LOG_ERR, 'Failed to connect to queue server');
483 throw new ServerException('Failed to connect to queue server');
490 * Subscribe to all enabled notice queues for the current site.
492 protected function doSubscribe()
494 $site = $this->currentSite();
496 foreach ($this->getQueues() as $queue) {
497 $rawqueue = $this->queueName($queue);
498 $this->subscriptions[$site][$queue] = $rawqueue;
499 $this->_log(LOG_INFO, "Subscribing to $rawqueue");
500 foreach ($this->cons as $con) {
502 $con->subscribe($rawqueue);
509 * Subscribe from all enabled notice queues for the current site.
511 protected function doUnsubscribe()
513 $site = $this->currentSite();
515 if (!empty($this->subscriptions[$site])) {
516 foreach ($this->subscriptions[$site] as $queue => $rawqueue) {
517 $this->_log(LOG_INFO, "Unsubscribing from $rawqueue");
518 foreach ($this->cons as $con) {
520 $con->unsubscribe($rawqueue);
523 unset($this->subscriptions[$site][$queue]);
529 * Handle and acknowledge an event that's come in through a queue.
531 * If the queue handler reports failure, the message is requeued for later.
532 * Missing notices or handler classes will drop the message.
534 * Side effects: in multi-site mode, may reset site configuration to
535 * match the site that queued the event.
537 * @param int $idx connection index
538 * @param StompFrame $frame
541 protected function handleItem($idx, $frame)
543 $this->defaultIdx = $idx;
545 list($site, $queue) = $this->parseDestination($frame->headers['destination']);
546 if ($site != $this->currentSite()) {
547 $this->stats('switch');
548 StatusNet::init($site);
551 $host = $this->cons[$idx]->getServer();
552 $item = $this->decode($frame->body);
554 $this->_log(LOG_ERR, "Skipping empty or deleted item in queue $queue from $host");
557 $info = $this->logrep($item) . " posted at " .
558 $frame->headers['created'] . " in queue $queue from $host";
559 $this->_log(LOG_DEBUG, "Dequeued $info");
561 $handler = $this->getHandler($queue);
563 $this->_log(LOG_ERR, "Missing handler class; skipping $info");
564 $this->ack($idx, $frame);
567 $this->stats('badhandler', $queue);
571 // If there's an exception when handling,
572 // log the error and let it get requeued.
575 $ok = $handler->handle($item);
576 } catch (Exception $e) {
577 $this->_log(LOG_ERR, "Exception on queue $queue: " . $e->getMessage());
582 $this->_log(LOG_WARNING, "Failed handling $info");
583 // FIXME we probably shouldn't have to do
584 // this kind of queue management ourselves;
585 // if we don't ack, it should resend...
586 $this->ack($idx, $frame);
587 $this->enqueue($item, $queue);
590 $this->stats('requeued', $queue);
594 $this->_log(LOG_INFO, "Successfully handled $info");
595 $this->ack($idx, $frame);
598 $this->stats('handled', $queue);
603 * Process a control signal broadcast.
605 * @param int $idx connection index
606 * @param array $frame Stomp frame
607 * @return bool true to continue; false to stop further processing.
609 protected function handleControlSignal($idx, $frame)
611 $message = trim($frame->body);
612 if (strpos($message, ':') !== false) {
613 list($event, $param) = explode(':', $message, 2);
621 if ($event == 'shutdown') {
622 $this->master->requestShutdown();
624 } else if ($event == 'restart') {
625 $this->master->requestRestart();
627 } else if ($event == 'update') {
628 $this->updateSiteConfig($param);
630 $this->_log(LOG_ERR, "Ignoring unrecognized control message: $message");
633 $this->ack($idx, $frame);
640 * Set us up with queue subscriptions for a new site added at runtime,
641 * triggered by a broadcast to the 'statusnet-control' topic.
643 * @param array $frame Stomp frame
644 * @return bool true to continue; false to stop further processing.
646 protected function updateSiteConfig($nickname)
648 if (empty($this->sites)) {
649 if ($nickname == common_config('site', 'nickname')) {
650 StatusNet::init(common_config('site', 'server'));
651 $this->doUnsubscribe();
652 $this->doSubscribe();
654 $this->_log(LOG_INFO, "Ignoring update ping for other site $nickname");
657 $sn = Status_network::staticGet($nickname);
659 $server = $sn->getServerName(); // @fixme do config-by-nick
660 StatusNet::init($server);
661 if (empty($this->sites[$server])) {
662 $this->addSite($server);
664 $this->_log(LOG_INFO, "(Re)subscribing to queues for site $nickname / $server");
665 $this->doUnsubscribe();
666 $this->doSubscribe();
667 $this->stats('siteupdate');
669 $this->_log(LOG_ERR, "Ignoring ping for unrecognized new site $nickname");
675 * Combines the queue_basename from configuration with the
676 * site server name and queue name to give eg:
678 * /queue/statusnet/identi.ca/sms
680 * @param string $queue
683 protected function queueName($queue)
685 return common_config('queue', 'queue_basename') .
686 $this->currentSite() . '/' . $queue;
690 * Returns the site and queue name from the server-side queue.
692 * @param string queue destination (eg '/queue/statusnet/identi.ca/sms')
693 * @return array of site and queue: ('identi.ca','sms') or false if unrecognized
695 protected function parseDestination($dest)
697 $prefix = common_config('queue', 'queue_basename');
698 if (substr($dest, 0, strlen($prefix)) == $prefix) {
699 $rest = substr($dest, strlen($prefix));
700 return explode("/", $rest, 2);
702 common_log(LOG_ERR, "Got a message from unrecognized stomp queue: $dest");
703 return array(false, false);
707 function _log($level, $msg)
709 common_log($level, 'StompQueueManager: '.$msg);
712 protected function begin($idx)
714 if ($this->useTransactions) {
715 if (!empty($this->transaction[$idx])) {
716 throw new Exception("Tried to start transaction in the middle of a transaction");
718 $this->transactionCount[$idx]++;
719 $this->transaction[$idx] = $this->master->id . '-' . $this->transactionCount[$idx] . '-' . time();
720 $this->cons[$idx]->begin($this->transaction[$idx]);
724 protected function ack($idx, $frame)
726 if ($this->useTransactions) {
727 if (empty($this->transaction[$idx])) {
728 throw new Exception("Tried to ack but not in a transaction");
730 $this->cons[$idx]->ack($frame, $this->transaction[$idx]);
732 $this->cons[$idx]->ack($frame);
736 protected function commit($idx)
738 if ($this->useTransactions) {
739 if (empty($this->transaction[$idx])) {
740 throw new Exception("Tried to commit but not in a transaction");
742 $this->cons[$idx]->commit($this->transaction[$idx]);
743 $this->transaction[$idx] = null;
747 protected function rollback($idx)
749 if ($this->useTransactions) {
750 if (empty($this->transaction[$idx])) {
751 throw new Exception("Tried to rollback but not in a transaction");
753 $this->cons[$idx]->commit($this->transaction[$idx]);
754 $this->transaction[$idx] = null;