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;
45 protected $sites = array();
46 protected $subscriptions = array();
48 protected $cons = array(); // all open connections
49 protected $disconnect = array();
50 protected $transaction = array();
51 protected $transactionCount = array();
52 protected $defaultIdx = 0;
54 function __construct()
56 parent::__construct();
57 $server = common_config('queue', 'stomp_server');
58 if (is_array($server)) {
59 $this->servers = $server;
61 $this->servers = array($server);
63 $this->username = common_config('queue', 'stomp_username');
64 $this->password = common_config('queue', 'stomp_password');
65 $this->base = common_config('queue', 'queue_basename');
66 $this->control = common_config('queue', 'control_channel');
67 $this->breakout = common_config('queue', 'breakout');
68 $this->useTransactions = common_config('queue', 'stomp_transactions');
69 $this->useAcks = common_config('queue', 'stomp_acks');
73 * Tell the i/o master we only need a single instance to cover
74 * all sites running in this process.
76 public static function multiSite()
78 return IoManager::INSTANCE_PER_PROCESS;
82 * Optional; ping any running queue handler daemons with a notification
83 * such as announcing a new site to handle or requesting clean shutdown.
84 * This avoids having to restart all the daemons manually to update configs
87 * Currently only relevant for multi-site queue managers such as Stomp.
89 * @param string $event event key
90 * @param string $param optional parameter to append to key
91 * @return boolean success
93 public function sendControlSignal($event, $param='')
97 $message .= ':' . $param;
100 $con = $this->cons[$this->defaultIdx];
101 $result = $con->send($this->control,
103 array ('created' => common_sql_now()));
105 $this->_log(LOG_INFO, "Sent control ping to queue daemons: $message");
108 $this->_log(LOG_ERR, "Failed sending control ping to queue daemons: $message");
114 * Saves an object into the queue item table.
116 * @param mixed $object
117 * @param string $queue
119 * @return boolean true on success
120 * @throws StompException on connection or send error
122 public function enqueue($object, $queue)
125 if (common_config('queue', 'stomp_enqueue_on')) {
126 // We're trying to force all writes to a single server.
127 // WARNING: this might do odd things if that server connection dies.
128 $idx = array_search(common_config('queue', 'stomp_enqueue_on'),
130 if ($idx === false) {
131 common_log(LOG_ERR, 'queue stomp_enqueue_on setting does not match our server list.');
132 $idx = $this->defaultIdx;
135 $idx = $this->defaultIdx;
137 return $this->_doEnqueue($object, $queue, $idx);
141 * Saves a notice object reference into the queue item table
142 * on the given connection.
144 * @return boolean true on success
145 * @throws StompException on connection or send error
147 protected function _doEnqueue($object, $queue, $idx)
149 $rep = $this->logrep($object);
150 $envelope = array('site' => common_config('site', 'nickname'),
152 'payload' => $this->encode($object));
153 $msg = serialize($envelope);
155 $props = array('created' => common_sql_now());
156 if ($this->isPersistent($queue)) {
157 $props['persistent'] = 'true';
160 $con = $this->cons[$idx];
161 $host = $con->getServer();
162 $target = $this->queueName($queue);
163 $result = $con->send($target, $msg, $props);
166 $this->_log(LOG_ERR, "Error sending $rep to $queue queue on $host $target");
170 $this->_log(LOG_DEBUG, "complete remote queueing $rep for $queue on $host $target");
171 $this->stats('enqueued', $queue);
176 * Determine whether messages to this queue should be marked as persistent.
177 * Actual persistent storage depends on the queue server's configuration.
178 * @param string $queue
181 protected function isPersistent($queue)
183 $mode = common_config('queue', 'stomp_persistent');
184 if (is_array($mode)) {
185 return in_array($queue, $mode);
192 * Send any sockets we're listening on to the IO manager
195 * @return array of resources
197 public function getSockets()
200 foreach ($this->cons as $con) {
202 $sockets[] = $con->getSocket();
209 * Get the Stomp connection object associated with the given socket.
210 * @param resource $socket
211 * @return int index into connections list
214 protected function connectionFromSocket($socket)
216 foreach ($this->cons as $i => $con) {
217 if ($con && $con->getSocket() === $socket) {
221 throw new Exception(__CLASS__ . " asked to read from unrecognized socket");
225 * We've got input to handle on our socket!
226 * Read any waiting Stomp frame(s) and process them.
228 * @param resource $socket
229 * @return boolean ok on success
231 public function handleInput($socket)
233 $idx = $this->connectionFromSocket($socket);
234 $con = $this->cons[$idx];
235 $host = $con->getServer();
236 $this->defaultIdx = $idx;
240 $frames = $con->readFrames();
241 } catch (StompException $e) {
242 $this->_log(LOG_ERR, "Lost connection to $host: " . $e->getMessage());
243 fclose($socket); // ???
244 $this->cons[$idx] = null;
245 $this->transaction[$idx] = null;
246 $this->disconnect[$idx] = time();
249 foreach ($frames as $frame) {
250 $dest = $frame->headers['destination'];
251 if ($dest == $this->control) {
252 if (!$this->handleControlSignal($frame)) {
253 // We got a control event that requests a shutdown;
254 // close out and stop handling anything else!
258 $ok = $this->handleItem($frame) && $ok;
260 $this->ack($idx, $frame);
268 * Attempt to reconnect in background if we lost a connection.
273 foreach ($this->cons as $idx => $con) {
275 $age = $now - $this->disconnect[$idx];
277 $this->_reconnect($idx);
285 * Initialize our connection and subscribe to all the queues
286 * we're going to need to handle... If multiple queue servers
287 * are configured for failover, we'll listen to all of them.
289 * Side effects: in multi-site mode, may reset site configuration.
291 * @param IoMaster $master process/event controller
292 * @return bool return false on failure
294 public function start($master)
296 parent::start($master);
297 $this->_connectAll();
299 foreach ($this->cons as $i => $con) {
301 $this->doSubscribe($con);
309 * Close out any active connections.
311 * @return bool return false on failure
313 public function finish()
315 // If there are any outstanding delivered messages we haven't processed,
316 // free them for another thread to take.
317 foreach ($this->cons as $i => $con) {
321 $this->cons[$i] = null;
328 * Lazy open a single connection to Stomp queue server.
329 * If multiple servers are configured, we let the Stomp client library
330 * worry about finding a working connection among them.
332 protected function _connect()
334 if (empty($this->cons)) {
335 $list = $this->servers;
336 if (count($list) > 1) {
337 shuffle($list); // Randomize to spread load
338 $url = 'failover://(' . implode(',', $list) . ')';
342 $con = $this->_doConnect($url);
343 $this->cons = array($con);
344 $this->transactionCount = array(0);
345 $this->transaction = array(null);
346 $this->disconnect = array(null);
351 * Lazy open connections to all Stomp servers, if in manual failover
352 * mode. This means the queue servers don't speak to each other, so
353 * we have to listen to all of them to make sure we get all events.
355 protected function _connectAll()
357 if (!common_config('queue', 'stomp_manual_failover')) {
358 return $this->_connect();
360 if (empty($this->cons)) {
361 $this->cons = array();
362 $this->transactionCount = array();
363 $this->transaction = array();
364 foreach ($this->servers as $idx => $server) {
366 $this->cons[] = $this->_doConnect($server);
367 $this->disconnect[] = null;
368 } catch (Exception $e) {
369 // s'okay, we'll live
370 $this->cons[] = null;
371 $this->disconnect[] = time();
373 $this->transactionCount[] = 0;
374 $this->transaction[] = null;
376 if (empty($this->cons)) {
377 throw new ServerException("No queue servers reachable...");
384 * Attempt to manually reconnect to the Stomp server for the given
385 * slot. If successful, set up our subscriptions on it.
387 protected function _reconnect($idx)
390 $con = $this->_doConnect($this->servers[$idx]);
391 } catch (Exception $e) {
392 $this->_log(LOG_ERR, $e->getMessage());
396 $this->cons[$idx] = $con;
397 $this->disconnect[$idx] = null;
399 $this->doSubscribe($con);
402 // Try again later...
403 $this->disconnect[$idx] = time();
407 protected function _doConnect($server)
409 $this->_log(LOG_INFO, "Connecting to '$server' as '$this->username'...");
410 $con = new LiberalStomp($server);
412 if ($con->connect($this->username, $this->password)) {
413 $this->_log(LOG_INFO, "Connected.");
415 $this->_log(LOG_ERR, 'Failed to connect to queue server');
416 throw new ServerException('Failed to connect to queue server');
423 * Set up all our raw queue subscriptions on the given connection
424 * @param LiberalStomp $con
426 protected function doSubscribe(LiberalStomp $con)
428 $host = $con->getServer();
429 foreach ($this->subscriptions() as $sub) {
430 $this->_log(LOG_INFO, "Subscribing to $sub on $host");
431 $con->subscribe($sub);
436 * Grab a full list of stomp-side queue subscriptions.
438 * - control broadcast channel
439 * - shared group queues for active groups
440 * - per-handler and per-site breakouts from $config['queue']['breakout']
441 * that are rooted in the active groups.
443 * @return array of strings
445 protected function subscriptions()
448 $subs[] = $this->control;
450 foreach ($this->activeGroups as $group) {
451 $subs[] = $this->base . $group;
454 foreach ($this->breakout as $spec) {
455 $parts = explode('/', $spec);
456 if (count($parts) < 2 || count($parts) > 3) {
457 common_log(LOG_ERR, "Bad queue breakout specifier $spec");
459 if (in_array($parts[0], $this->activeGroups)) {
460 $subs[] = $this->base . $spec;
463 return array_unique($subs);
467 * Handle and acknowledge an event that's come in through a queue.
469 * If the queue handler reports failure, the message is requeued for later.
470 * Missing notices or handler classes will drop the message.
472 * Side effects: in multi-site mode, may reset site configuration to
473 * match the site that queued the event.
475 * @param StompFrame $frame
476 * @return bool success
478 protected function handleItem($frame)
480 $host = $this->cons[$this->defaultIdx]->getServer();
481 $message = unserialize($frame->body);
482 $site = $message['site'];
483 $queue = $message['handler'];
485 if ($this->isDeadletter($frame, $message)) {
486 $this->stats('deadletter', $queue);
490 // @fixme detect failing site switches
491 $this->switchSite($site);
493 $item = $this->decode($message['payload']);
495 $this->_log(LOG_ERR, "Skipping empty or deleted item in queue $queue from $host");
496 $this->stats('baditem', $queue);
499 $info = $this->logrep($item) . " posted at " .
500 $frame->headers['created'] . " in queue $queue from $host";
501 $this->_log(LOG_DEBUG, "Dequeued $info");
503 $handler = $this->getHandler($queue);
505 $this->_log(LOG_ERR, "Missing handler class; skipping $info");
506 $this->stats('badhandler', $queue);
511 $ok = $handler->handle($item);
512 } catch (Exception $e) {
513 $this->_log(LOG_ERR, "Exception on queue $queue: " . $e->getMessage());
518 $this->_log(LOG_INFO, "Successfully handled $info");
519 $this->stats('handled', $queue);
521 $this->_log(LOG_WARNING, "Failed handling $info");
522 // Requeing moves the item to the end of the line for its next try.
523 // @fixme add a manual retry count
524 $this->enqueue($item, $queue);
525 $this->stats('requeued', $queue);
532 * Check if a redelivered message has been run through enough
533 * that we're going to give up on it.
535 * @param StompFrame $frame
536 * @param array $message unserialized message body
537 * @return boolean true if we should discard
539 protected function isDeadLetter($frame, $message)
541 if (isset($frame->headers['redelivered']) && $frame->headers['redelivered'] == 'true') {
542 // Message was redelivered, possibly indicating a previous failure.
543 $msgId = $frame->headers['message-id'];
544 $site = $message['site'];
545 $queue = $message['handler'];
546 $msgInfo = "message $msgId for $site in queue $queue";
548 $deliveries = $this->incDeliveryCount($msgId);
549 if ($deliveries > common_config('queue', 'max_retries')) {
550 $info = "DEAD-LETTER FILE: Gave up after retry $deliveries on $msgInfo";
552 $outdir = common_config('queue', 'dead_letter_dir');
554 $filename = $outdir . "/$site-$queue-" . rawurlencode($msgId);
555 $info .= ": dumping to $filename";
556 file_put_contents($filename, $message['payload']);
559 common_log(LOG_ERR, $info);
562 common_log(LOG_INFO, "retry $deliveries on $msgInfo");
569 * Update count of times we've re-encountered this message recently,
570 * triggered when we get a message marked as 'redelivered'.
572 * Requires a CLI-friendly cache configuration.
574 * @param string $msgId message-id header from message
575 * @return int number of retries recorded
577 function incDeliveryCount($msgId)
580 $cache = common_memcache();
582 $key = 'statusnet:stomp:message-retries:' . $msgId;
583 $count = $cache->increment($key);
586 $cache->set($key, $count, null, 3600);
587 $got = $cache->get($key);
594 * Process a control signal broadcast.
596 * @param int $idx connection index
597 * @param array $frame Stomp frame
598 * @return bool true to continue; false to stop further processing.
600 protected function handleControlSignal($idx, $frame)
602 $message = trim($frame->body);
603 if (strpos($message, ':') !== false) {
604 list($event, $param) = explode(':', $message, 2);
612 if ($event == 'shutdown') {
613 $this->master->requestShutdown();
615 } else if ($event == 'restart') {
616 $this->master->requestRestart();
618 } else if ($event == 'update') {
619 $this->updateSiteConfig($param);
621 $this->_log(LOG_ERR, "Ignoring unrecognized control message: $message");
627 * Switch site, if necessary, and reset current handler assignments
628 * @param string $site
630 function switchSite($site)
632 if ($site != StatusNet::currentSite()) {
633 $this->stats('switch');
634 StatusNet::switchSite($site);
640 * (Re)load runtime configuration for a given site by nickname,
641 * triggered by a broadcast to the 'statusnet-control' topic.
643 * Configuration changes in database should update, but config
646 * @param array $frame Stomp frame
647 * @return bool true to continue; false to stop further processing.
649 protected function updateSiteConfig($nickname)
651 $sn = Status_network::staticGet($nickname);
653 $this->switchSite($nickname);
654 if (!in_array($nickname, $this->sites)) {
657 $this->stats('siteupdate');
659 $this->_log(LOG_ERR, "Ignoring ping for unrecognized new site $nickname");
664 * Combines the queue_basename from configuration with the
665 * group name for this queue to give eg:
667 * /queue/statusnet/main
668 * /queue/statusnet/main/distrib
669 * /queue/statusnet/xmpp/xmppout/site01
671 * @param string $queue
674 protected function queueName($queue)
676 $group = $this->queueGroup($queue);
677 $site = StatusNet::currentSite();
679 $specs = array("$group/$queue/$site",
681 foreach ($specs as $spec) {
682 if (in_array($spec, $this->breakout)) {
683 return $this->base . $spec;
686 return $this->base . $group;
690 * Get the breakout mode for the given queue on the current site.
692 * @param string $queue
693 * @return string one of 'shared', 'handler', 'site'
695 protected function breakoutMode($queue)
697 $breakout = common_config('queue', 'breakout');
698 if (isset($breakout[$queue])) {
699 return $breakout[$queue];
700 } else if (isset($breakout['*'])) {
701 return $breakout['*'];
707 protected function begin($idx)
709 if ($this->useTransactions) {
710 if (!empty($this->transaction[$idx])) {
711 throw new Exception("Tried to start transaction in the middle of a transaction");
713 $this->transactionCount[$idx]++;
714 $this->transaction[$idx] = $this->master->id . '-' . $this->transactionCount[$idx] . '-' . time();
715 $this->cons[$idx]->begin($this->transaction[$idx]);
719 protected function ack($idx, $frame)
721 if ($this->useAcks) {
722 if ($this->useTransactions) {
723 if (empty($this->transaction[$idx])) {
724 throw new Exception("Tried to ack but not in a transaction");
726 $this->cons[$idx]->ack($frame, $this->transaction[$idx]);
728 $this->cons[$idx]->ack($frame);
733 protected function commit($idx)
735 if ($this->useTransactions) {
736 if (empty($this->transaction[$idx])) {
737 throw new Exception("Tried to commit but not in a transaction");
739 $this->cons[$idx]->commit($this->transaction[$idx]);
740 $this->transaction[$idx] = null;
744 protected function rollback($idx)
746 if ($this->useTransactions) {
747 if (empty($this->transaction[$idx])) {
748 throw new Exception("Tried to rollback but not in a transaction");
750 $this->cons[$idx]->commit($this->transaction[$idx]);
751 $this->transaction[$idx] = null;