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';
34 class StompQueueManager extends QueueManager
42 protected $sites = array();
44 protected $useTransactions = true;
45 protected $transaction = null;
46 protected $transactionCount = 0;
48 function __construct()
50 parent::__construct();
51 $this->server = common_config('queue', 'stomp_server');
52 $this->username = common_config('queue', 'stomp_username');
53 $this->password = common_config('queue', 'stomp_password');
54 $this->base = common_config('queue', 'queue_basename');
58 * Tell the i/o master we only need a single instance to cover
59 * all sites running in this process.
61 public static function multiSite()
63 return IoManager::INSTANCE_PER_PROCESS;
67 * Record each site we'll be handling input for in this process,
68 * so we can listen to the necessary queues for it.
70 * @fixme possibly actually do subscription here to save another
71 * loop over all sites later?
72 * @fixme possibly don't assume it's the current site
74 public function addSite($server)
76 $this->sites[] = $server;
82 * Instantiate the appropriate QueueHandler class for the given queue.
84 * @param string $queue
85 * @return mixed QueueHandler or null
87 function getHandler($queue)
89 $handlers = $this->handlers[common_config('site', 'server')];
90 if (isset($handlers[$queue])) {
91 $class = $handlers[$queue];
92 if (class_exists($class)) {
95 common_log(LOG_ERR, "Nonexistent handler class '$class' for queue '$queue'");
98 common_log(LOG_ERR, "Requested handler for unkown queue '$queue'");
104 * Get a list of all registered queue transport names.
106 * @return array of strings
110 $group = $this->activeGroup();
111 $site = common_config('site', 'server');
112 if (empty($this->groups[$site][$group])) {
115 return array_keys($this->groups[$site][$group]);
120 * Register a queue transport name and handler class for your plugin.
121 * Only registered transports will be reliably picked up!
123 * @param string $transport
124 * @param string $class
125 * @param string $group
127 public function connect($transport, $class, $group='queuedaemon')
129 $this->handlers[common_config('site', 'server')][$transport] = $class;
130 $this->groups[common_config('site', 'server')][$group][$transport] = $class;
134 * Saves a notice object reference into the queue item table.
135 * @return boolean true on success
137 public function enqueue($object, $queue)
139 $msg = $this->encode($object);
140 $rep = $this->logrep($object);
144 // XXX: serialize and send entire notice
146 $result = $this->con->send($this->queueName($queue),
147 $msg, // BODY of the message
148 array ('created' => common_sql_now()));
151 common_log(LOG_ERR, "Error sending $rep to $queue queue");
155 common_log(LOG_DEBUG, "complete remote queueing $rep for $queue");
156 $this->stats('enqueued', $queue);
160 * Send any sockets we're listening on to the IO manager
163 * @return array of resources
165 public function getSockets()
167 return array($this->con->getSocket());
171 * We've got input to handle on our socket!
172 * Read any waiting Stomp frame(s) and process them.
174 * @param resource $socket
175 * @return boolean ok on success
177 public function handleInput($socket)
179 assert($socket === $this->con->getSocket());
181 $frames = $this->con->readFrames();
182 foreach ($frames as $frame) {
183 $ok = $ok && $this->_handleItem($frame);
189 * Initialize our connection and subscribe to all the queues
190 * we're going to need to handle...
192 * Side effects: in multi-site mode, may reset site configuration.
194 * @param IoMaster $master process/event controller
195 * @return bool return false on failure
197 public function start($master)
199 parent::start($master);
201 foreach ($this->sites as $server) {
202 StatusNet::init($server);
203 $this->doSubscribe();
206 $this->doSubscribe();
213 * Subscribe to all the queues we're going to need to handle...
215 * Side effects: in multi-site mode, may reset site configuration.
217 * @return bool return false on failure
219 public function finish()
221 // If there are any outstanding delivered messages we haven't processed,
222 // free them for another thread to take.
225 foreach ($this->sites as $server) {
226 StatusNet::init($server);
227 $this->doUnsubscribe();
230 $this->doUnsubscribe();
236 * Lazy open connection to Stomp queue server.
238 protected function _connect()
240 if (empty($this->con)) {
241 $this->_log(LOG_INFO, "Connecting to '$this->server' as '$this->username'...");
242 $this->con = new LiberalStomp($this->server);
244 if ($this->con->connect($this->username, $this->password)) {
245 $this->_log(LOG_INFO, "Connected.");
247 $this->_log(LOG_ERR, 'Failed to connect to queue server');
248 throw new ServerException('Failed to connect to queue server');
254 * Subscribe to all enabled notice queues for the current site.
256 protected function doSubscribe()
259 foreach ($this->getQueues() as $queue) {
260 $rawqueue = $this->queueName($queue);
261 $this->_log(LOG_INFO, "Subscribing to $rawqueue");
262 $this->con->subscribe($rawqueue);
267 * Subscribe from all enabled notice queues for the current site.
269 protected function doUnsubscribe()
272 foreach ($this->getQueues() as $queue) {
273 $this->con->unsubscribe($this->queueName($queue));
278 * Handle and acknowledge an event that's come in through a queue.
280 * If the queue handler reports failure, the message is requeued for later.
281 * Missing notices or handler classes will drop the message.
283 * Side effects: in multi-site mode, may reset site configuration to
284 * match the site that queued the event.
286 * @param StompFrame $frame
289 protected function _handleItem($frame)
291 list($site, $queue) = $this->parseDestination($frame->headers['destination']);
292 if ($site != common_config('site', 'server')) {
293 $this->stats('switch');
294 StatusNet::init($site);
297 if (is_numeric($frame->body)) {
298 $id = intval($frame->body);
299 $info = "notice $id posted at {$frame->headers['created']} in queue $queue";
301 $notice = Notice::staticGet('id', $id);
302 if (empty($notice)) {
303 $this->_log(LOG_WARNING, "Skipping missing $info");
307 $this->stats('badnotice', $queue);
313 // @fixme should we serialize, or json, or what here?
314 $info = "string posted at {$frame->headers['created']} in queue $queue";
315 $item = $frame->body;
318 $handler = $this->getHandler($queue);
320 $this->_log(LOG_ERROR, "Missing handler class; skipping $info");
324 $this->stats('badhandler', $queue);
328 $ok = $handler->handle($item);
331 $this->_log(LOG_WARNING, "Failed handling $info");
332 // FIXME we probably shouldn't have to do
333 // this kind of queue management ourselves;
334 // if we don't ack, it should resend...
336 $this->enqueue($item, $queue);
339 $this->stats('requeued', $queue);
343 $this->_log(LOG_INFO, "Successfully handled $info");
347 $this->stats('handled', $queue);
352 * Combines the queue_basename from configuration with the
353 * site server name and queue name to give eg:
355 * /queue/statusnet/identi.ca/sms
357 * @param string $queue
360 protected function queueName($queue)
362 return common_config('queue', 'queue_basename') .
363 common_config('site', 'server') . '/' . $queue;
367 * Returns the site and queue name from the server-side queue.
369 * @param string queue destination (eg '/queue/statusnet/identi.ca/sms')
370 * @return array of site and queue: ('identi.ca','sms') or false if unrecognized
372 protected function parseDestination($dest)
374 $prefix = common_config('queue', 'queue_basename');
375 if (substr($dest, 0, strlen($prefix)) == $prefix) {
376 $rest = substr($dest, strlen($prefix));
377 return explode("/", $rest, 2);
379 common_log(LOG_ERR, "Got a message from unrecognized stomp queue: $dest");
380 return array(false, false);
384 function _log($level, $msg)
386 common_log($level, 'StompQueueManager: '.$msg);
389 protected function begin()
391 if ($this->useTransactions) {
392 if ($this->transaction) {
393 throw new Exception("Tried to start transaction in the middle of a transaction");
395 $this->transactionCount++;
396 $this->transaction = $this->master->id . '-' . $this->transactionCount . '-' . time();
397 $this->con->begin($this->transaction);
401 protected function ack($frame)
403 if ($this->useTransactions) {
404 if (!$this->transaction) {
405 throw new Exception("Tried to ack but not in a transaction");
408 $this->con->ack($frame, $this->transaction);
411 protected function commit()
413 if ($this->useTransactions) {
414 if (!$this->transaction) {
415 throw new Exception("Tried to commit but not in a transaction");
417 $this->con->commit($this->transaction);
418 $this->transaction = null;
422 protected function rollback()
424 if ($this->useTransactions) {
425 if (!$this->transaction) {
426 throw new Exception("Tried to rollback but not in a transaction");
428 $this->con->commit($this->transaction);
429 $this->transaction = null;