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');
66 $this->subscriptions = array($this->control => $this->control);
70 * Tell the i/o master we only need a single instance to cover
71 * all sites running in this process.
73 public static function multiSite()
75 return IoManager::INSTANCE_PER_PROCESS;
79 * Record queue subscriptions we'll need to handle the current site.
81 public function addSite()
83 $this->sites[] = StatusNet::currentSite();
85 // Set up handlers active for this site...
88 foreach ($this->activeGroups as $group) {
89 if (isset($this->groups[$group])) {
90 // Actual queues may be broken out or consolidated...
91 // Subscribe to all the target queues we'll need.
92 foreach ($this->groups[$group] as $transport => $class) {
93 $target = $this->queueName($transport);
94 $this->subscriptions[$target] = $target;
101 * Optional; ping any running queue handler daemons with a notification
102 * such as announcing a new site to handle or requesting clean shutdown.
103 * This avoids having to restart all the daemons manually to update configs
106 * Currently only relevant for multi-site queue managers such as Stomp.
108 * @param string $event event key
109 * @param string $param optional parameter to append to key
110 * @return boolean success
112 public function sendControlSignal($event, $param='')
116 $message .= ':' . $param;
119 $con = $this->cons[$this->defaultIdx];
120 $result = $con->send($this->control,
122 array ('created' => common_sql_now()));
124 $this->_log(LOG_INFO, "Sent control ping to queue daemons: $message");
127 $this->_log(LOG_ERR, "Failed sending control ping to queue daemons: $message");
133 * Saves an object into the queue item table.
135 * @param mixed $object
136 * @param string $queue
138 * @return boolean true on success
139 * @throws StompException on connection or send error
141 public function enqueue($object, $queue)
144 return $this->_doEnqueue($object, $queue, $this->defaultIdx);
148 * Saves a notice object reference into the queue item table
149 * on the given connection.
151 * @return boolean true on success
152 * @throws StompException on connection or send error
154 protected function _doEnqueue($object, $queue, $idx)
156 $rep = $this->logrep($object);
157 $envelope = array('site' => common_config('site', 'nickname'),
159 'payload' => $this->encode($object));
160 $msg = serialize($envelope);
162 $props = array('created' => common_sql_now());
163 if ($this->isPersistent($queue)) {
164 $props['persistent'] = 'true';
167 $con = $this->cons[$idx];
168 $host = $con->getServer();
169 $result = $con->send($this->queueName($queue), $msg, $props);
172 $this->_log(LOG_ERR, "Error sending $rep to $queue queue on $host");
176 $this->_log(LOG_DEBUG, "complete remote queueing $rep for $queue on $host");
177 $this->stats('enqueued', $queue);
182 * Determine whether messages to this queue should be marked as persistent.
183 * Actual persistent storage depends on the queue server's configuration.
184 * @param string $queue
187 protected function isPersistent($queue)
189 $mode = common_config('queue', 'stomp_persistent');
190 if (is_array($mode)) {
191 return in_array($queue, $mode);
198 * Send any sockets we're listening on to the IO manager
201 * @return array of resources
203 public function getSockets()
206 foreach ($this->cons as $con) {
208 $sockets[] = $con->getSocket();
215 * Get the Stomp connection object associated with the given socket.
216 * @param resource $socket
217 * @return int index into connections list
220 protected function connectionFromSocket($socket)
222 foreach ($this->cons as $i => $con) {
223 if ($con && $con->getSocket() === $socket) {
227 throw new Exception(__CLASS__ . " asked to read from unrecognized socket");
231 * We've got input to handle on our socket!
232 * Read any waiting Stomp frame(s) and process them.
234 * @param resource $socket
235 * @return boolean ok on success
237 public function handleInput($socket)
239 $idx = $this->connectionFromSocket($socket);
240 $con = $this->cons[$idx];
241 $host = $con->getServer();
242 $this->defaultIdx = $idx;
246 $frames = $con->readFrames();
247 } catch (StompException $e) {
248 $this->_log(LOG_ERR, "Lost connection to $host: " . $e->getMessage());
249 fclose($socket); // ???
250 $this->cons[$idx] = null;
251 $this->transaction[$idx] = null;
252 $this->disconnect[$idx] = time();
255 foreach ($frames as $frame) {
256 $dest = $frame->headers['destination'];
257 if ($dest == $this->control) {
258 if (!$this->handleControlSignal($frame)) {
259 // We got a control event that requests a shutdown;
260 // close out and stop handling anything else!
264 $ok = $this->handleItem($frame) && $ok;
266 $this->ack($idx, $frame);
274 * Attempt to reconnect in background if we lost a connection.
279 foreach ($this->cons as $idx => $con) {
281 $age = $now - $this->disconnect[$idx];
283 $this->_reconnect($idx);
291 * Initialize our connection and subscribe to all the queues
292 * we're going to need to handle... If multiple queue servers
293 * are configured for failover, we'll listen to all of them.
295 * Side effects: in multi-site mode, may reset site configuration.
297 * @param IoMaster $master process/event controller
298 * @return bool return false on failure
300 public function start($master)
302 parent::start($master);
303 $this->_connectAll();
305 foreach ($this->cons as $i => $con) {
307 $this->doSubscribe($con);
315 * Close out any active connections.
317 * @return bool return false on failure
319 public function finish()
321 // If there are any outstanding delivered messages we haven't processed,
322 // free them for another thread to take.
323 foreach ($this->cons as $i => $con) {
327 $this->cons[$i] = null;
334 * Lazy open a single connection to Stomp queue server.
335 * If multiple servers are configured, we let the Stomp client library
336 * worry about finding a working connection among them.
338 protected function _connect()
340 if (empty($this->cons)) {
341 $list = $this->servers;
342 if (count($list) > 1) {
343 shuffle($list); // Randomize to spread load
344 $url = 'failover://(' . implode(',', $list) . ')';
348 $con = $this->_doConnect($url);
349 $this->cons = array($con);
350 $this->transactionCount = array(0);
351 $this->transaction = array(null);
352 $this->disconnect = array(null);
357 * Lazy open connections to all Stomp servers, if in manual failover
358 * mode. This means the queue servers don't speak to each other, so
359 * we have to listen to all of them to make sure we get all events.
361 protected function _connectAll()
363 if (!common_config('queue', 'stomp_manual_failover')) {
364 return $this->_connect();
366 if (empty($this->cons)) {
367 $this->cons = array();
368 $this->transactionCount = array();
369 $this->transaction = array();
370 foreach ($this->servers as $idx => $server) {
372 $this->cons[] = $this->_doConnect($server);
373 $this->disconnect[] = null;
374 } catch (Exception $e) {
375 // s'okay, we'll live
376 $this->cons[] = null;
377 $this->disconnect[] = time();
379 $this->transactionCount[] = 0;
380 $this->transaction[] = null;
382 if (empty($this->cons)) {
383 throw new ServerException("No queue servers reachable...");
390 * Attempt to manually reconnect to the Stomp server for the given
391 * slot. If successful, set up our subscriptions on it.
393 protected function _reconnect($idx)
396 $con = $this->_doConnect($this->servers[$idx]);
397 } catch (Exception $e) {
398 $this->_log(LOG_ERR, $e->getMessage());
402 $this->cons[$idx] = $con;
403 $this->disconnect[$idx] = null;
405 $this->doSubscribe($con);
408 // Try again later...
409 $this->disconnect[$idx] = time();
413 protected function _doConnect($server)
415 $this->_log(LOG_INFO, "Connecting to '$server' as '$this->username'...");
416 $con = new LiberalStomp($server);
418 if ($con->connect($this->username, $this->password)) {
419 $this->_log(LOG_INFO, "Connected.");
421 $this->_log(LOG_ERR, 'Failed to connect to queue server');
422 throw new ServerException('Failed to connect to queue server');
429 * Set up all our raw queue subscriptions on the given connection
430 * @param LiberalStomp $con
432 protected function doSubscribe(LiberalStomp $con)
434 $host = $con->getServer();
435 foreach ($this->subscriptions as $queue) {
436 $this->_log(LOG_INFO, "Subscribing to $queue on $host");
437 $con->subscribe($queue);
442 * Handle and acknowledge an event that's come in through a queue.
444 * If the queue handler reports failure, the message is requeued for later.
445 * Missing notices or handler classes will drop the message.
447 * Side effects: in multi-site mode, may reset site configuration to
448 * match the site that queued the event.
450 * @param StompFrame $frame
451 * @return bool success
453 protected function handleItem($frame)
455 $host = $this->cons[$this->defaultIdx]->getServer();
456 $message = unserialize($frame->body);
457 $site = $message['site'];
458 $queue = $message['handler'];
460 if ($this->isDeadletter($frame, $message)) {
461 $this->stats('deadletter', $queue);
465 // @fixme detect failing site switches
466 $this->switchSite($site);
468 $item = $this->decode($message['payload']);
470 $this->_log(LOG_ERR, "Skipping empty or deleted item in queue $queue from $host");
471 $this->stats('baditem', $queue);
474 $info = $this->logrep($item) . " posted at " .
475 $frame->headers['created'] . " in queue $queue from $host";
476 $this->_log(LOG_DEBUG, "Dequeued $info");
478 $handler = $this->getHandler($queue);
480 $this->_log(LOG_ERR, "Missing handler class; skipping $info");
481 $this->stats('badhandler', $queue);
486 $ok = $handler->handle($item);
487 } catch (Exception $e) {
488 $this->_log(LOG_ERR, "Exception on queue $queue: " . $e->getMessage());
493 $this->_log(LOG_INFO, "Successfully handled $info");
494 $this->stats('handled', $queue);
496 $this->_log(LOG_WARNING, "Failed handling $info");
497 // Requeing moves the item to the end of the line for its next try.
498 // @fixme add a manual retry count
499 $this->enqueue($item, $queue);
500 $this->stats('requeued', $queue);
507 * Check if a redelivered message has been run through enough
508 * that we're going to give up on it.
510 * @param StompFrame $frame
511 * @param array $message unserialized message body
512 * @return boolean true if we should discard
514 protected function isDeadLetter($frame, $message)
516 if (isset($frame->headers['redelivered']) && $frame->headers['redelivered'] == 'true') {
517 // Message was redelivered, possibly indicating a previous failure.
518 $msgId = $frame->headers['message-id'];
519 $site = $message['site'];
520 $queue = $message['handler'];
521 $msgInfo = "message $msgId for $site in queue $queue";
523 $deliveries = $this->incDeliveryCount($msgId);
524 if ($deliveries > common_config('queue', 'max_retries')) {
525 $info = "DEAD-LETTER FILE: Gave up after retry $deliveries on $msgInfo";
527 $outdir = common_config('queue', 'dead_letter_dir');
529 $filename = $outdir . "/$site-$queue-" . rawurlencode($msgId);
530 $info .= ": dumping to $filename";
531 file_put_contents($filename, $message['payload']);
534 common_log(LOG_ERR, $info);
537 common_log(LOG_INFO, "retry $deliveries on $msgInfo");
544 * Update count of times we've re-encountered this message recently,
545 * triggered when we get a message marked as 'redelivered'.
547 * Requires a CLI-friendly cache configuration.
549 * @param string $msgId message-id header from message
550 * @return int number of retries recorded
552 function incDeliveryCount($msgId)
555 $cache = common_memcache();
557 $key = 'statusnet:stomp:message-retries:' . $msgId;
558 $count = $cache->increment($key);
561 $cache->set($key, $count, null, 3600);
562 $got = $cache->get($key);
569 * Process a control signal broadcast.
571 * @param int $idx connection index
572 * @param array $frame Stomp frame
573 * @return bool true to continue; false to stop further processing.
575 protected function handleControlSignal($idx, $frame)
577 $message = trim($frame->body);
578 if (strpos($message, ':') !== false) {
579 list($event, $param) = explode(':', $message, 2);
587 if ($event == 'shutdown') {
588 $this->master->requestShutdown();
590 } else if ($event == 'restart') {
591 $this->master->requestRestart();
593 } else if ($event == 'update') {
594 $this->updateSiteConfig($param);
596 $this->_log(LOG_ERR, "Ignoring unrecognized control message: $message");
602 * Switch site, if necessary, and reset current handler assignments
603 * @param string $site
605 function switchSite($site)
607 if ($site != StatusNet::currentSite()) {
608 $this->stats('switch');
609 StatusNet::switchSite($site);
615 * Set us up with queue subscriptions for a new site added at runtime,
616 * triggered by a broadcast to the 'statusnet-control' topic.
618 * @param array $frame Stomp frame
619 * @return bool true to continue; false to stop further processing.
621 protected function updateSiteConfig($nickname)
623 if (empty($this->sites)) {
624 if ($nickname == common_config('site', 'nickname')) {
625 StatusNet::init(common_config('site', 'server'));
627 $this->_log(LOG_INFO, "Ignoring update ping for other site $nickname");
630 $sn = Status_network::staticGet($nickname);
632 $this->switchSite($nickname);
633 if (!in_array($nickname, $this->sites)) {
636 // @fixme update subscriptions, if applicable
637 $this->stats('siteupdate');
639 $this->_log(LOG_ERR, "Ignoring ping for unrecognized new site $nickname");
645 * Combines the queue_basename from configuration with the
646 * group name for this queue to give eg:
648 * /queue/statusnet/main
650 * @param string $queue
653 protected function queueName($queue)
655 $base = common_config('queue', 'queue_basename');
656 $group = $this->queueGroup($queue);
657 $breakout = $this->breakoutMode($queue);
658 if ($breakout == 'shared') {
659 return $base . "$group";
660 } else if ($breakout == 'handler') {
661 return $base . "$group/$queue";
662 } else if ($breakout == 'site') {
663 $site = StatusNet::currentSite();
664 return $base . "$group/$queue/$site";
666 throw Exception("Unrecognized queue breakout mode '$breakout' for '$queue'");
670 * Get the breakout mode for the given queue on the current site.
672 * @param string $queue
673 * @return string one of 'shared', 'handler', 'site'
675 protected function breakoutMode($queue)
677 $breakout = common_config('queue', 'breakout');
678 if (isset($breakout[$queue])) {
679 return $breakout[$queue];
680 } else if (isset($breakout['*'])) {
681 return $breakout['*'];
687 protected function begin($idx)
689 if ($this->useTransactions) {
690 if (!empty($this->transaction[$idx])) {
691 throw new Exception("Tried to start transaction in the middle of a transaction");
693 $this->transactionCount[$idx]++;
694 $this->transaction[$idx] = $this->master->id . '-' . $this->transactionCount[$idx] . '-' . time();
695 $this->cons[$idx]->begin($this->transaction[$idx]);
699 protected function ack($idx, $frame)
701 if ($this->useTransactions) {
702 if (empty($this->transaction[$idx])) {
703 throw new Exception("Tried to ack but not in a transaction");
705 $this->cons[$idx]->ack($frame, $this->transaction[$idx]);
707 $this->cons[$idx]->ack($frame);
711 protected function commit($idx)
713 if ($this->useTransactions) {
714 if (empty($this->transaction[$idx])) {
715 throw new Exception("Tried to commit but not in a transaction");
717 $this->cons[$idx]->commit($this->transaction[$idx]);
718 $this->transaction[$idx] = null;
722 protected function rollback($idx)
724 if ($this->useTransactions) {
725 if (empty($this->transaction[$idx])) {
726 throw new Exception("Tried to rollback but not in a transaction");
728 $this->cons[$idx]->commit($this->transaction[$idx]);
729 $this->transaction[$idx] = null;