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 return $this->_doEnqueue($object, $queue, $this->defaultIdx);
129 * Saves a notice object reference into the queue item table
130 * on the given connection.
132 * @return boolean true on success
133 * @throws StompException on connection or send error
135 protected function _doEnqueue($object, $queue, $idx)
137 $rep = $this->logrep($object);
138 $envelope = array('site' => common_config('site', 'nickname'),
140 'payload' => $this->encode($object));
141 $msg = serialize($envelope);
143 $props = array('created' => common_sql_now());
144 if ($this->isPersistent($queue)) {
145 $props['persistent'] = 'true';
148 $con = $this->cons[$idx];
149 $host = $con->getServer();
150 $target = $this->queueName($queue);
151 $result = $con->send($target, $msg, $props);
154 $this->_log(LOG_ERR, "Error sending $rep to $queue queue on $host $target");
158 $this->_log(LOG_DEBUG, "complete remote queueing $rep for $queue on $host $target");
159 $this->stats('enqueued', $queue);
164 * Determine whether messages to this queue should be marked as persistent.
165 * Actual persistent storage depends on the queue server's configuration.
166 * @param string $queue
169 protected function isPersistent($queue)
171 $mode = common_config('queue', 'stomp_persistent');
172 if (is_array($mode)) {
173 return in_array($queue, $mode);
180 * Send any sockets we're listening on to the IO manager
183 * @return array of resources
185 public function getSockets()
188 foreach ($this->cons as $con) {
190 $sockets[] = $con->getSocket();
197 * Get the Stomp connection object associated with the given socket.
198 * @param resource $socket
199 * @return int index into connections list
202 protected function connectionFromSocket($socket)
204 foreach ($this->cons as $i => $con) {
205 if ($con && $con->getSocket() === $socket) {
209 throw new Exception(__CLASS__ . " asked to read from unrecognized socket");
213 * We've got input to handle on our socket!
214 * Read any waiting Stomp frame(s) and process them.
216 * @param resource $socket
217 * @return boolean ok on success
219 public function handleInput($socket)
221 $idx = $this->connectionFromSocket($socket);
222 $con = $this->cons[$idx];
223 $host = $con->getServer();
224 $this->defaultIdx = $idx;
228 $frames = $con->readFrames();
229 } catch (StompException $e) {
230 $this->_log(LOG_ERR, "Lost connection to $host: " . $e->getMessage());
231 fclose($socket); // ???
232 $this->cons[$idx] = null;
233 $this->transaction[$idx] = null;
234 $this->disconnect[$idx] = time();
237 foreach ($frames as $frame) {
238 $dest = $frame->headers['destination'];
239 if ($dest == $this->control) {
240 if (!$this->handleControlSignal($frame)) {
241 // We got a control event that requests a shutdown;
242 // close out and stop handling anything else!
246 $ok = $this->handleItem($frame) && $ok;
248 $this->ack($idx, $frame);
256 * Attempt to reconnect in background if we lost a connection.
261 foreach ($this->cons as $idx => $con) {
263 $age = $now - $this->disconnect[$idx];
265 $this->_reconnect($idx);
273 * Initialize our connection and subscribe to all the queues
274 * we're going to need to handle... If multiple queue servers
275 * are configured for failover, we'll listen to all of them.
277 * Side effects: in multi-site mode, may reset site configuration.
279 * @param IoMaster $master process/event controller
280 * @return bool return false on failure
282 public function start($master)
284 parent::start($master);
285 $this->_connectAll();
287 foreach ($this->cons as $i => $con) {
289 $this->doSubscribe($con);
297 * Close out any active connections.
299 * @return bool return false on failure
301 public function finish()
303 // If there are any outstanding delivered messages we haven't processed,
304 // free them for another thread to take.
305 foreach ($this->cons as $i => $con) {
309 $this->cons[$i] = null;
316 * Lazy open a single connection to Stomp queue server.
317 * If multiple servers are configured, we let the Stomp client library
318 * worry about finding a working connection among them.
320 protected function _connect()
322 if (empty($this->cons)) {
323 $list = $this->servers;
324 if (count($list) > 1) {
325 shuffle($list); // Randomize to spread load
326 $url = 'failover://(' . implode(',', $list) . ')';
330 $con = $this->_doConnect($url);
331 $this->cons = array($con);
332 $this->transactionCount = array(0);
333 $this->transaction = array(null);
334 $this->disconnect = array(null);
339 * Lazy open connections to all Stomp servers, if in manual failover
340 * mode. This means the queue servers don't speak to each other, so
341 * we have to listen to all of them to make sure we get all events.
343 protected function _connectAll()
345 if (!common_config('queue', 'stomp_manual_failover')) {
346 return $this->_connect();
348 if (empty($this->cons)) {
349 $this->cons = array();
350 $this->transactionCount = array();
351 $this->transaction = array();
352 foreach ($this->servers as $idx => $server) {
354 $this->cons[] = $this->_doConnect($server);
355 $this->disconnect[] = null;
356 } catch (Exception $e) {
357 // s'okay, we'll live
358 $this->cons[] = null;
359 $this->disconnect[] = time();
361 $this->transactionCount[] = 0;
362 $this->transaction[] = null;
364 if (empty($this->cons)) {
365 throw new ServerException("No queue servers reachable...");
372 * Attempt to manually reconnect to the Stomp server for the given
373 * slot. If successful, set up our subscriptions on it.
375 protected function _reconnect($idx)
378 $con = $this->_doConnect($this->servers[$idx]);
379 } catch (Exception $e) {
380 $this->_log(LOG_ERR, $e->getMessage());
384 $this->cons[$idx] = $con;
385 $this->disconnect[$idx] = null;
387 $this->doSubscribe($con);
390 // Try again later...
391 $this->disconnect[$idx] = time();
395 protected function _doConnect($server)
397 $this->_log(LOG_INFO, "Connecting to '$server' as '$this->username'...");
398 $con = new LiberalStomp($server);
400 if ($con->connect($this->username, $this->password)) {
401 $this->_log(LOG_INFO, "Connected.");
403 $this->_log(LOG_ERR, 'Failed to connect to queue server');
404 throw new ServerException('Failed to connect to queue server');
411 * Set up all our raw queue subscriptions on the given connection
412 * @param LiberalStomp $con
414 protected function doSubscribe(LiberalStomp $con)
416 $host = $con->getServer();
417 foreach ($this->subscriptions() as $sub) {
418 $this->_log(LOG_INFO, "Subscribing to $sub on $host");
419 $con->subscribe($sub);
424 * Grab a full list of stomp-side queue subscriptions.
426 * - control broadcast channel
427 * - shared group queues for active groups
428 * - per-handler and per-site breakouts from $config['queue']['breakout']
429 * that are rooted in the active groups.
431 * @return array of strings
433 protected function subscriptions()
436 $subs[] = $this->control;
438 foreach ($this->activeGroups as $group) {
439 $subs[] = $this->base . $group;
442 foreach ($this->breakout as $spec) {
443 $parts = explode('/', $spec);
444 if (count($parts) < 2 || count($parts) > 3) {
445 common_log(LOG_ERR, "Bad queue breakout specifier $spec");
447 if (in_array($parts[0], $this->activeGroups)) {
448 $subs[] = $this->base . $spec;
451 return array_unique($subs);
455 * Handle and acknowledge an event that's come in through a queue.
457 * If the queue handler reports failure, the message is requeued for later.
458 * Missing notices or handler classes will drop the message.
460 * Side effects: in multi-site mode, may reset site configuration to
461 * match the site that queued the event.
463 * @param StompFrame $frame
464 * @return bool success
466 protected function handleItem($frame)
468 $host = $this->cons[$this->defaultIdx]->getServer();
469 $message = unserialize($frame->body);
470 $site = $message['site'];
471 $queue = $message['handler'];
473 if ($this->isDeadletter($frame, $message)) {
474 $this->stats('deadletter', $queue);
478 // @fixme detect failing site switches
479 $this->switchSite($site);
481 $item = $this->decode($message['payload']);
483 $this->_log(LOG_ERR, "Skipping empty or deleted item in queue $queue from $host");
484 $this->stats('baditem', $queue);
487 $info = $this->logrep($item) . " posted at " .
488 $frame->headers['created'] . " in queue $queue from $host";
489 $this->_log(LOG_DEBUG, "Dequeued $info");
491 $handler = $this->getHandler($queue);
493 $this->_log(LOG_ERR, "Missing handler class; skipping $info");
494 $this->stats('badhandler', $queue);
499 $ok = $handler->handle($item);
500 } catch (Exception $e) {
501 $this->_log(LOG_ERR, "Exception on queue $queue: " . $e->getMessage());
506 $this->_log(LOG_INFO, "Successfully handled $info");
507 $this->stats('handled', $queue);
509 $this->_log(LOG_WARNING, "Failed handling $info");
510 // Requeing moves the item to the end of the line for its next try.
511 // @fixme add a manual retry count
512 $this->enqueue($item, $queue);
513 $this->stats('requeued', $queue);
520 * Check if a redelivered message has been run through enough
521 * that we're going to give up on it.
523 * @param StompFrame $frame
524 * @param array $message unserialized message body
525 * @return boolean true if we should discard
527 protected function isDeadLetter($frame, $message)
529 if (isset($frame->headers['redelivered']) && $frame->headers['redelivered'] == 'true') {
530 // Message was redelivered, possibly indicating a previous failure.
531 $msgId = $frame->headers['message-id'];
532 $site = $message['site'];
533 $queue = $message['handler'];
534 $msgInfo = "message $msgId for $site in queue $queue";
536 $deliveries = $this->incDeliveryCount($msgId);
537 if ($deliveries > common_config('queue', 'max_retries')) {
538 $info = "DEAD-LETTER FILE: Gave up after retry $deliveries on $msgInfo";
540 $outdir = common_config('queue', 'dead_letter_dir');
542 $filename = $outdir . "/$site-$queue-" . rawurlencode($msgId);
543 $info .= ": dumping to $filename";
544 file_put_contents($filename, $message['payload']);
547 common_log(LOG_ERR, $info);
550 common_log(LOG_INFO, "retry $deliveries on $msgInfo");
557 * Update count of times we've re-encountered this message recently,
558 * triggered when we get a message marked as 'redelivered'.
560 * Requires a CLI-friendly cache configuration.
562 * @param string $msgId message-id header from message
563 * @return int number of retries recorded
565 function incDeliveryCount($msgId)
568 $cache = common_memcache();
570 $key = 'statusnet:stomp:message-retries:' . $msgId;
571 $count = $cache->increment($key);
574 $cache->set($key, $count, null, 3600);
575 $got = $cache->get($key);
582 * Process a control signal broadcast.
584 * @param int $idx connection index
585 * @param array $frame Stomp frame
586 * @return bool true to continue; false to stop further processing.
588 protected function handleControlSignal($idx, $frame)
590 $message = trim($frame->body);
591 if (strpos($message, ':') !== false) {
592 list($event, $param) = explode(':', $message, 2);
600 if ($event == 'shutdown') {
601 $this->master->requestShutdown();
603 } else if ($event == 'restart') {
604 $this->master->requestRestart();
606 } else if ($event == 'update') {
607 $this->updateSiteConfig($param);
609 $this->_log(LOG_ERR, "Ignoring unrecognized control message: $message");
615 * Switch site, if necessary, and reset current handler assignments
616 * @param string $site
618 function switchSite($site)
620 if ($site != StatusNet::currentSite()) {
621 $this->stats('switch');
622 StatusNet::switchSite($site);
628 * (Re)load runtime configuration for a given site by nickname,
629 * triggered by a broadcast to the 'statusnet-control' topic.
631 * Configuration changes in database should update, but config
634 * @param array $frame Stomp frame
635 * @return bool true to continue; false to stop further processing.
637 protected function updateSiteConfig($nickname)
639 $sn = Status_network::staticGet($nickname);
641 $this->switchSite($nickname);
642 if (!in_array($nickname, $this->sites)) {
645 $this->stats('siteupdate');
647 $this->_log(LOG_ERR, "Ignoring ping for unrecognized new site $nickname");
652 * Combines the queue_basename from configuration with the
653 * group name for this queue to give eg:
655 * /queue/statusnet/main
656 * /queue/statusnet/main/distrib
657 * /queue/statusnet/xmpp/xmppout/site01
659 * @param string $queue
662 protected function queueName($queue)
664 $group = $this->queueGroup($queue);
665 $site = StatusNet::currentSite();
667 $specs = array("$group/$queue/$site",
669 foreach ($specs as $spec) {
670 if (in_array($spec, $this->breakout)) {
671 return $this->base . $spec;
674 return $this->base . $group;
678 * Get the breakout mode for the given queue on the current site.
680 * @param string $queue
681 * @return string one of 'shared', 'handler', 'site'
683 protected function breakoutMode($queue)
685 $breakout = common_config('queue', 'breakout');
686 if (isset($breakout[$queue])) {
687 return $breakout[$queue];
688 } else if (isset($breakout['*'])) {
689 return $breakout['*'];
695 protected function begin($idx)
697 if ($this->useTransactions) {
698 if (!empty($this->transaction[$idx])) {
699 throw new Exception("Tried to start transaction in the middle of a transaction");
701 $this->transactionCount[$idx]++;
702 $this->transaction[$idx] = $this->master->id . '-' . $this->transactionCount[$idx] . '-' . time();
703 $this->cons[$idx]->begin($this->transaction[$idx]);
707 protected function ack($idx, $frame)
709 if ($this->useAcks) {
710 if ($this->useTransactions) {
711 if (empty($this->transaction[$idx])) {
712 throw new Exception("Tried to ack but not in a transaction");
714 $this->cons[$idx]->ack($frame, $this->transaction[$idx]);
716 $this->cons[$idx]->ack($frame);
721 protected function commit($idx)
723 if ($this->useTransactions) {
724 if (empty($this->transaction[$idx])) {
725 throw new Exception("Tried to commit but not in a transaction");
727 $this->cons[$idx]->commit($this->transaction[$idx]);
728 $this->transaction[$idx] = null;
732 protected function rollback($idx)
734 if ($this->useTransactions) {
735 if (empty($this->transaction[$idx])) {
736 throw new Exception("Tried to rollback but not in a transaction");
738 $this->cons[$idx]->commit($this->transaction[$idx]);
739 $this->transaction[$idx] = null;