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);
484 if ($message === false) {
485 $this->_log(LOG_ERR, "Can't unserialize frame: {$frame->body}");
486 $this->_log(LOG_ERR, "Unserializable frame length: " . strlen($frame->body));
490 $site = $message['site'];
491 $queue = $message['handler'];
493 if ($this->isDeadletter($frame, $message)) {
494 $this->stats('deadletter', $queue);
498 // @fixme detect failing site switches
499 $this->switchSite($site);
502 $item = $this->decode($message['payload']);
503 } catch (Exception $e) {
504 $this->_log(LOG_ERR, "Skipping empty or deleted item in queue $queue from $host");
505 $this->stats('baditem', $queue);
508 $info = $this->logrep($item) . " posted at " .
509 $frame->headers['created'] . " in queue $queue from $host";
510 $this->_log(LOG_DEBUG, "Dequeued $info");
512 $handler = $this->getHandler($queue);
514 $this->_log(LOG_ERR, "Missing handler class; skipping $info");
515 $this->stats('badhandler', $queue);
520 $ok = $handler->handle($item);
521 } catch (Exception $e) {
522 $this->_log(LOG_ERR, "Exception on queue $queue: " . $e->getMessage());
527 $this->_log(LOG_INFO, "Successfully handled $info");
528 $this->stats('handled', $queue);
530 $this->_log(LOG_WARNING, "Failed handling $info");
531 // Requeing moves the item to the end of the line for its next try.
532 // @fixme add a manual retry count
533 $this->enqueue($item, $queue);
534 $this->stats('requeued', $queue);
541 * Check if a redelivered message has been run through enough
542 * that we're going to give up on it.
544 * @param StompFrame $frame
545 * @param array $message unserialized message body
546 * @return boolean true if we should discard
548 protected function isDeadLetter($frame, $message)
550 if (isset($frame->headers['redelivered']) && $frame->headers['redelivered'] == 'true') {
551 // Message was redelivered, possibly indicating a previous failure.
552 $msgId = $frame->headers['message-id'];
553 $site = $message['site'];
554 $queue = $message['handler'];
555 $msgInfo = "message $msgId for $site in queue $queue";
557 $deliveries = $this->incDeliveryCount($msgId);
558 if ($deliveries > common_config('queue', 'max_retries')) {
559 $info = "DEAD-LETTER FILE: Gave up after retry $deliveries on $msgInfo";
561 $outdir = common_config('queue', 'dead_letter_dir');
563 $filename = $outdir . "/$site-$queue-" . rawurlencode($msgId);
564 $info .= ": dumping to $filename";
565 file_put_contents($filename, $message['payload']);
568 common_log(LOG_ERR, $info);
571 common_log(LOG_INFO, "retry $deliveries on $msgInfo");
578 * Update count of times we've re-encountered this message recently,
579 * triggered when we get a message marked as 'redelivered'.
581 * Requires a CLI-friendly cache configuration.
583 * @param string $msgId message-id header from message
584 * @return int number of retries recorded
586 function incDeliveryCount($msgId)
589 $cache = Cache::instance();
591 $key = 'statusnet:stomp:message-retries:' . $msgId;
592 $count = $cache->increment($key);
595 $cache->set($key, $count, null, 3600);
596 $got = $cache->get($key);
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");
636 * Switch site, if necessary, and reset current handler assignments
637 * @param string $site
639 function switchSite($site)
641 if ($site != StatusNet::currentSite()) {
642 $this->stats('switch');
643 StatusNet::switchSite($site);
649 * (Re)load runtime configuration for a given site by nickname,
650 * triggered by a broadcast to the 'statusnet-control' topic.
652 * Configuration changes in database should update, but config
655 * @param array $frame Stomp frame
656 * @return bool true to continue; false to stop further processing.
658 protected function updateSiteConfig($nickname)
660 $sn = Status_network::getKV('nickname', $nickname);
662 $this->switchSite($nickname);
663 if (!in_array($nickname, $this->sites)) {
666 $this->stats('siteupdate');
668 $this->_log(LOG_ERR, "Ignoring ping for unrecognized new site $nickname");
673 * Combines the queue_basename from configuration with the
674 * group name for this queue to give eg:
676 * /queue/statusnet/main
677 * /queue/statusnet/main/distrib
678 * /queue/statusnet/xmpp/xmppout/site01
680 * @param string $queue
683 protected function queueName($queue)
685 $group = $this->queueGroup($queue);
686 $site = StatusNet::currentSite();
688 $specs = array("$group/$queue/$site",
690 foreach ($specs as $spec) {
691 if (in_array($spec, $this->breakout)) {
692 return $this->base . $spec;
695 return $this->base . $group;
699 * Get the breakout mode for the given queue on the current site.
701 * @param string $queue
702 * @return string one of 'shared', 'handler', 'site'
704 protected function breakoutMode($queue)
706 $breakout = common_config('queue', 'breakout');
707 if (isset($breakout[$queue])) {
708 return $breakout[$queue];
709 } else if (isset($breakout['*'])) {
710 return $breakout['*'];
716 protected function begin($idx)
718 if ($this->useTransactions) {
719 if (!empty($this->transaction[$idx])) {
720 throw new Exception("Tried to start transaction in the middle of a transaction");
722 $this->transactionCount[$idx]++;
723 $this->transaction[$idx] = $this->master->id . '-' . $this->transactionCount[$idx] . '-' . time();
724 $this->cons[$idx]->begin($this->transaction[$idx]);
728 protected function ack($idx, $frame)
730 if ($this->useAcks) {
731 if ($this->useTransactions) {
732 if (empty($this->transaction[$idx])) {
733 throw new Exception("Tried to ack but not in a transaction");
735 $this->cons[$idx]->ack($frame, $this->transaction[$idx]);
737 $this->cons[$idx]->ack($frame);
742 protected function commit($idx)
744 if ($this->useTransactions) {
745 if (empty($this->transaction[$idx])) {
746 throw new Exception("Tried to commit but not in a transaction");
748 $this->cons[$idx]->commit($this->transaction[$idx]);
749 $this->transaction[$idx] = null;
753 protected function rollback($idx)
755 if ($this->useTransactions) {
756 if (empty($this->transaction[$idx])) {
757 throw new Exception("Tried to rollback but not in a transaction");
759 $this->cons[$idx]->commit($this->transaction[$idx]);
760 $this->transaction[$idx] = null;