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
118 * @param string $siteNickname optional override to drop into another site's queue
120 * @return boolean true on success
121 * @throws StompException on connection or send error
123 public function enqueue($object, $queue, $siteNickname=null)
126 if (common_config('queue', 'stomp_enqueue_on')) {
127 // We're trying to force all writes to a single server.
128 // WARNING: this might do odd things if that server connection dies.
129 $idx = array_search(common_config('queue', 'stomp_enqueue_on'),
131 if ($idx === false) {
132 common_log(LOG_ERR, 'queue stomp_enqueue_on setting does not match our server list.');
133 $idx = $this->defaultIdx;
136 $idx = $this->defaultIdx;
138 return $this->_doEnqueue($object, $queue, $idx, $siteNickname);
142 * Saves a notice object reference into the queue item table
143 * on the given connection.
145 * @return boolean true on success
146 * @throws StompException on connection or send error
148 protected function _doEnqueue($object, $queue, $idx, $siteNickname=null)
150 $rep = $this->logrep($object);
151 $envelope = array('site' => $siteNickname ? $siteNickname : common_config('site', 'nickname'),
153 'payload' => $this->encode($object));
154 $msg = serialize($envelope);
156 $props = array('created' => common_sql_now());
157 if ($this->isPersistent($queue)) {
158 $props['persistent'] = 'true';
161 $con = $this->cons[$idx];
162 $host = $con->getServer();
163 $target = $this->queueName($queue);
164 $result = $con->send($target, $msg, $props);
167 $this->_log(LOG_ERR, "Error sending $rep to $queue queue on $host $target");
171 $this->_log(LOG_DEBUG, "complete remote queueing $rep for $queue on $host $target");
172 $this->stats('enqueued', $queue);
177 * Determine whether messages to this queue should be marked as persistent.
178 * Actual persistent storage depends on the queue server's configuration.
179 * @param string $queue
182 protected function isPersistent($queue)
184 $mode = common_config('queue', 'stomp_persistent');
185 if (is_array($mode)) {
186 return in_array($queue, $mode);
193 * Send any sockets we're listening on to the IO manager
196 * @return array of resources
198 public function getSockets()
201 foreach ($this->cons as $con) {
203 $sockets[] = $con->getSocket();
210 * Get the Stomp connection object associated with the given socket.
211 * @param resource $socket
212 * @return int index into connections list
215 protected function connectionFromSocket($socket)
217 foreach ($this->cons as $i => $con) {
218 if ($con && $con->getSocket() === $socket) {
222 throw new Exception(__CLASS__ . " asked to read from unrecognized socket");
226 * We've got input to handle on our socket!
227 * Read any waiting Stomp frame(s) and process them.
229 * @param resource $socket
230 * @return boolean ok on success
232 public function handleInput($socket)
234 $idx = $this->connectionFromSocket($socket);
235 $con = $this->cons[$idx];
236 $host = $con->getServer();
237 $this->defaultIdx = $idx;
241 $frames = $con->readFrames();
242 } catch (StompException $e) {
243 $this->_log(LOG_ERR, "Lost connection to $host: " . $e->getMessage());
244 fclose($socket); // ???
245 $this->cons[$idx] = null;
246 $this->transaction[$idx] = null;
247 $this->disconnect[$idx] = time();
250 foreach ($frames as $frame) {
251 $dest = $frame->headers['destination'];
252 if ($dest == $this->control) {
253 if (!$this->handleControlSignal($frame)) {
254 // We got a control event that requests a shutdown;
255 // close out and stop handling anything else!
259 $ok = $this->handleItem($frame) && $ok;
261 $this->ack($idx, $frame);
269 * Attempt to reconnect in background if we lost a connection.
274 foreach ($this->cons as $idx => $con) {
276 $age = $now - $this->disconnect[$idx];
278 $this->_reconnect($idx);
286 * Initialize our connection and subscribe to all the queues
287 * we're going to need to handle... If multiple queue servers
288 * are configured for failover, we'll listen to all of them.
290 * Side effects: in multi-site mode, may reset site configuration.
292 * @param IoMaster $master process/event controller
293 * @return bool return false on failure
295 public function start($master)
297 parent::start($master);
298 $this->_connectAll();
300 foreach ($this->cons as $i => $con) {
302 $this->doSubscribe($con);
310 * Close out any active connections.
312 * @return bool return false on failure
314 public function finish()
316 // If there are any outstanding delivered messages we haven't processed,
317 // free them for another thread to take.
318 foreach ($this->cons as $i => $con) {
322 $this->cons[$i] = null;
329 * Lazy open a single connection to Stomp queue server.
330 * If multiple servers are configured, we let the Stomp client library
331 * worry about finding a working connection among them.
333 protected function _connect()
335 if (empty($this->cons)) {
336 $list = $this->servers;
337 if (count($list) > 1) {
338 shuffle($list); // Randomize to spread load
339 $url = 'failover://(' . implode(',', $list) . ')';
343 $con = $this->_doConnect($url);
344 $this->cons = array($con);
345 $this->transactionCount = array(0);
346 $this->transaction = array(null);
347 $this->disconnect = array(null);
352 * Lazy open connections to all Stomp servers, if in manual failover
353 * mode. This means the queue servers don't speak to each other, so
354 * we have to listen to all of them to make sure we get all events.
356 protected function _connectAll()
358 if (!common_config('queue', 'stomp_manual_failover')) {
359 return $this->_connect();
361 if (empty($this->cons)) {
362 $this->cons = array();
363 $this->transactionCount = array();
364 $this->transaction = array();
365 foreach ($this->servers as $idx => $server) {
367 $this->cons[] = $this->_doConnect($server);
368 $this->disconnect[] = null;
369 } catch (Exception $e) {
370 // s'okay, we'll live
371 $this->cons[] = null;
372 $this->disconnect[] = time();
374 $this->transactionCount[] = 0;
375 $this->transaction[] = null;
377 if (empty($this->cons)) {
378 throw new ServerException("No queue servers reachable...");
385 * Attempt to manually reconnect to the Stomp server for the given
386 * slot. If successful, set up our subscriptions on it.
388 protected function _reconnect($idx)
391 $con = $this->_doConnect($this->servers[$idx]);
392 } catch (Exception $e) {
393 $this->_log(LOG_ERR, $e->getMessage());
397 $this->cons[$idx] = $con;
398 $this->disconnect[$idx] = null;
400 $this->doSubscribe($con);
403 // Try again later...
404 $this->disconnect[$idx] = time();
408 protected function _doConnect($server)
410 $this->_log(LOG_INFO, "Connecting to '$server' as '$this->username'...");
411 $con = new LiberalStomp($server);
413 if ($con->connect($this->username, $this->password)) {
414 $this->_log(LOG_INFO, "Connected.");
416 $this->_log(LOG_ERR, 'Failed to connect to queue server');
417 throw new ServerException('Failed to connect to queue server');
424 * Set up all our raw queue subscriptions on the given connection
425 * @param LiberalStomp $con
427 protected function doSubscribe(LiberalStomp $con)
429 $host = $con->getServer();
430 foreach ($this->subscriptions() as $sub) {
431 $this->_log(LOG_INFO, "Subscribing to $sub on $host");
432 $con->subscribe($sub);
437 * Grab a full list of stomp-side queue subscriptions.
439 * - control broadcast channel
440 * - shared group queues for active groups
441 * - per-handler and per-site breakouts from $config['queue']['breakout']
442 * that are rooted in the active groups.
444 * @return array of strings
446 protected function subscriptions()
449 $subs[] = $this->control;
451 foreach ($this->activeGroups as $group) {
452 $subs[] = $this->base . $group;
455 foreach ($this->breakout as $spec) {
456 $parts = explode('/', $spec);
457 if (count($parts) < 2 || count($parts) > 3) {
458 common_log(LOG_ERR, "Bad queue breakout specifier $spec");
460 if (in_array($parts[0], $this->activeGroups)) {
461 $subs[] = $this->base . $spec;
464 return array_unique($subs);
468 * Handle and acknowledge an event that's come in through a queue.
470 * If the queue handler reports failure, the message is requeued for later.
471 * Missing notices or handler classes will drop the message.
473 * Side effects: in multi-site mode, may reset site configuration to
474 * match the site that queued the event.
476 * @param StompFrame $frame
477 * @return bool success
479 protected function handleItem($frame)
481 $host = $this->cons[$this->defaultIdx]->getServer();
482 $message = unserialize($frame->body);
483 $site = $message['site'];
484 $queue = $message['handler'];
486 if ($this->isDeadletter($frame, $message)) {
487 $this->stats('deadletter', $queue);
491 // @fixme detect failing site switches
492 $this->switchSite($site);
494 $item = $this->decode($message['payload']);
496 $this->_log(LOG_ERR, "Skipping empty or deleted item in queue $queue from $host");
497 $this->stats('baditem', $queue);
500 $info = $this->logrep($item) . " posted at " .
501 $frame->headers['created'] . " in queue $queue from $host";
502 $this->_log(LOG_DEBUG, "Dequeued $info");
504 $handler = $this->getHandler($queue);
506 $this->_log(LOG_ERR, "Missing handler class; skipping $info");
507 $this->stats('badhandler', $queue);
512 $ok = $handler->handle($item);
513 } catch (Exception $e) {
514 $this->_log(LOG_ERR, "Exception on queue $queue: " . $e->getMessage());
519 $this->_log(LOG_INFO, "Successfully handled $info");
520 $this->stats('handled', $queue);
522 $this->_log(LOG_WARNING, "Failed handling $info");
523 // Requeing moves the item to the end of the line for its next try.
524 // @fixme add a manual retry count
525 $this->enqueue($item, $queue);
526 $this->stats('requeued', $queue);
533 * Check if a redelivered message has been run through enough
534 * that we're going to give up on it.
536 * @param StompFrame $frame
537 * @param array $message unserialized message body
538 * @return boolean true if we should discard
540 protected function isDeadLetter($frame, $message)
542 if (isset($frame->headers['redelivered']) && $frame->headers['redelivered'] == 'true') {
543 // Message was redelivered, possibly indicating a previous failure.
544 $msgId = $frame->headers['message-id'];
545 $site = $message['site'];
546 $queue = $message['handler'];
547 $msgInfo = "message $msgId for $site in queue $queue";
549 $deliveries = $this->incDeliveryCount($msgId);
550 if ($deliveries > common_config('queue', 'max_retries')) {
551 $info = "DEAD-LETTER FILE: Gave up after retry $deliveries on $msgInfo";
553 $outdir = common_config('queue', 'dead_letter_dir');
555 $filename = $outdir . "/$site-$queue-" . rawurlencode($msgId);
556 $info .= ": dumping to $filename";
557 file_put_contents($filename, $message['payload']);
560 common_log(LOG_ERR, $info);
563 common_log(LOG_INFO, "retry $deliveries on $msgInfo");
570 * Update count of times we've re-encountered this message recently,
571 * triggered when we get a message marked as 'redelivered'.
573 * Requires a CLI-friendly cache configuration.
575 * @param string $msgId message-id header from message
576 * @return int number of retries recorded
578 function incDeliveryCount($msgId)
581 $cache = Cache::instance();
583 $key = 'statusnet:stomp:message-retries:' . $msgId;
584 $count = $cache->increment($key);
587 $cache->set($key, $count, null, 3600);
588 $got = $cache->get($key);
595 * Process a control signal broadcast.
597 * @param int $idx connection index
598 * @param array $frame Stomp frame
599 * @return bool true to continue; false to stop further processing.
601 protected function handleControlSignal($idx, $frame)
603 $message = trim($frame->body);
604 if (strpos($message, ':') !== false) {
605 list($event, $param) = explode(':', $message, 2);
613 if ($event == 'shutdown') {
614 $this->master->requestShutdown();
616 } else if ($event == 'restart') {
617 $this->master->requestRestart();
619 } else if ($event == 'update') {
620 $this->updateSiteConfig($param);
622 $this->_log(LOG_ERR, "Ignoring unrecognized control message: $message");
628 * Switch site, if necessary, and reset current handler assignments
629 * @param string $site
631 function switchSite($site)
633 if ($site != StatusNet::currentSite()) {
634 $this->stats('switch');
635 StatusNet::switchSite($site);
641 * (Re)load runtime configuration for a given site by nickname,
642 * triggered by a broadcast to the 'statusnet-control' topic.
644 * Configuration changes in database should update, but config
647 * @param array $frame Stomp frame
648 * @return bool true to continue; false to stop further processing.
650 protected function updateSiteConfig($nickname)
652 $sn = Status_network::staticGet('nickname', $nickname);
654 $this->switchSite($nickname);
655 if (!in_array($nickname, $this->sites)) {
658 $this->stats('siteupdate');
660 $this->_log(LOG_ERR, "Ignoring ping for unrecognized new site $nickname");
665 * Combines the queue_basename from configuration with the
666 * group name for this queue to give eg:
668 * /queue/statusnet/main
669 * /queue/statusnet/main/distrib
670 * /queue/statusnet/xmpp/xmppout/site01
672 * @param string $queue
675 protected function queueName($queue)
677 $group = $this->queueGroup($queue);
678 $site = StatusNet::currentSite();
680 $specs = array("$group/$queue/$site",
682 foreach ($specs as $spec) {
683 if (in_array($spec, $this->breakout)) {
684 return $this->base . $spec;
687 return $this->base . $group;
691 * Get the breakout mode for the given queue on the current site.
693 * @param string $queue
694 * @return string one of 'shared', 'handler', 'site'
696 protected function breakoutMode($queue)
698 $breakout = common_config('queue', 'breakout');
699 if (isset($breakout[$queue])) {
700 return $breakout[$queue];
701 } else if (isset($breakout['*'])) {
702 return $breakout['*'];
708 protected function begin($idx)
710 if ($this->useTransactions) {
711 if (!empty($this->transaction[$idx])) {
712 throw new Exception("Tried to start transaction in the middle of a transaction");
714 $this->transactionCount[$idx]++;
715 $this->transaction[$idx] = $this->master->id . '-' . $this->transactionCount[$idx] . '-' . time();
716 $this->cons[$idx]->begin($this->transaction[$idx]);
720 protected function ack($idx, $frame)
722 if ($this->useAcks) {
723 if ($this->useTransactions) {
724 if (empty($this->transaction[$idx])) {
725 throw new Exception("Tried to ack but not in a transaction");
727 $this->cons[$idx]->ack($frame, $this->transaction[$idx]);
729 $this->cons[$idx]->ack($frame);
734 protected function commit($idx)
736 if ($this->useTransactions) {
737 if (empty($this->transaction[$idx])) {
738 throw new Exception("Tried to commit but not in a transaction");
740 $this->cons[$idx]->commit($this->transaction[$idx]);
741 $this->transaction[$idx] = null;
745 protected function rollback($idx)
747 if ($this->useTransactions) {
748 if (empty($this->transaction[$idx])) {
749 throw new Exception("Tried to rollback but not in a transaction");
751 $this->cons[$idx]->commit($this->transaction[$idx]);
752 $this->transaction[$idx] = null;