summaryrefslogtreecommitdiff
path: root/lib/stompqueuemanager.php
blob: 8f0091a1384f51b1cf07ad6c4bddf7dfbd920f03 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Abstract class for queue managers
 *
 * PHP version 5
 *
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  QueueManager
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @author    Sarven Capadisli <csarven@status.net>
 * @copyright 2009 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://status.net/
 */

require_once 'Stomp.php';


class StompQueueManager extends QueueManager
{
    var $server = null;
    var $username = null;
    var $password = null;
    var $base = null;
    var $con = null;
    
    protected $sites = array();

    protected $useTransactions = true;
    protected $transaction = null;
    protected $transactionCount = 0;

    function __construct()
    {
        parent::__construct();
        $this->server   = common_config('queue', 'stomp_server');
        $this->username = common_config('queue', 'stomp_username');
        $this->password = common_config('queue', 'stomp_password');
        $this->base     = common_config('queue', 'queue_basename');
    }

    /**
     * Tell the i/o master we only need a single instance to cover
     * all sites running in this process.
     */
    public static function multiSite()
    {
        return IoManager::INSTANCE_PER_PROCESS;
    }

    /**
     * Record each site we'll be handling input for in this process,
     * so we can listen to the necessary queues for it.
     *
     * @fixme possibly actually do subscription here to save another
     *        loop over all sites later?
     * @fixme possibly don't assume it's the current site
     */
    public function addSite($server)
    {
        $this->sites[] = $server;
        $this->initialize();
    }


    /**
     * Instantiate the appropriate QueueHandler class for the given queue.
     *
     * @param string $queue
     * @return mixed QueueHandler or null
     */
    function getHandler($queue)
    {
        $handlers = $this->handlers[common_config('site', 'server')];
        if (isset($handlers[$queue])) {
            $class = $handlers[$queue];
            if (class_exists($class)) {
                return new $class();
            } else {
                common_log(LOG_ERR, "Nonexistent handler class '$class' for queue '$queue'");
            }
        } else {
            common_log(LOG_ERR, "Requested handler for unkown queue '$queue'");
        }
        return null;
    }

    /**
     * Get a list of all registered queue transport names.
     *
     * @return array of strings
     */
    function getQueues()
    {
        $group = $this->activeGroup();
        $site = common_config('site', 'server');
        if (empty($this->groups[$site][$group])) {
            return array();
        } else {
            return array_keys($this->groups[$site][$group]);
        }
    }

    /**
     * Register a queue transport name and handler class for your plugin.
     * Only registered transports will be reliably picked up!
     *
     * @param string $transport
     * @param string $class
     * @param string $group
     */
    public function connect($transport, $class, $group='queuedaemon')
    {
        $this->handlers[common_config('site', 'server')][$transport] = $class;
        $this->groups[common_config('site', 'server')][$group][$transport] = $class;
    }

    /**
     * Saves a notice object reference into the queue item table.
     * @return boolean true on success
     */
    public function enqueue($object, $queue)
    {
        $msg = $this->encode($object);
        $rep = $this->logrep($object);

        $this->_connect();

        // XXX: serialize and send entire notice

        $result = $this->con->send($this->queueName($queue),
                                   $msg, 		// BODY of the message
                                   array ('created' => common_sql_now()));

        if (!$result) {
            common_log(LOG_ERR, "Error sending $rep to $queue queue");
            return false;
        }

        common_log(LOG_DEBUG, "complete remote queueing $rep for $queue");
        $this->stats('enqueued', $queue);
    }

    /**
     * Send any sockets we're listening on to the IO manager
     * to wait for input.
     *
     * @return array of resources
     */
    public function getSockets()
    {
        return array($this->con->getSocket());
    }

    /**
     * We've got input to handle on our socket!
     * Read any waiting Stomp frame(s) and process them.
     *
     * @param resource $socket
     * @return boolean ok on success
     */
    public function handleInput($socket)
    {
        assert($socket === $this->con->getSocket());
        $ok = true;
        $frames = $this->con->readFrames();
        foreach ($frames as $frame) {
            $ok = $ok && $this->_handleItem($frame);
        }
        return $ok;
    }

    /**
     * Initialize our connection and subscribe to all the queues
     * we're going to need to handle...
     *
     * Side effects: in multi-site mode, may reset site configuration.
     *
     * @param IoMaster $master process/event controller
     * @return bool return false on failure
     */
    public function start($master)
    {
        parent::start($master);
        if ($this->sites) {
            foreach ($this->sites as $server) {
                StatusNet::init($server);
                $this->doSubscribe();
            }
        } else {
            $this->doSubscribe();
        }
        $this->begin();
        return true;
    }
    
    /**
     * Subscribe to all the queues we're going to need to handle...
     *
     * Side effects: in multi-site mode, may reset site configuration.
     *
     * @return bool return false on failure
     */
    public function finish()
    {
        // If there are any outstanding delivered messages we haven't processed,
        // free them for another thread to take.
        $this->rollback();
        if ($this->sites) {
            foreach ($this->sites as $server) {
                StatusNet::init($server);
                $this->doUnsubscribe();
            }
        } else {
            $this->doUnsubscribe();
        }
        return true;
    }
    
    /**
     * Lazy open connection to Stomp queue server.
     */
    protected function _connect()
    {
        if (empty($this->con)) {
            $this->_log(LOG_INFO, "Connecting to '$this->server' as '$this->username'...");
            $this->con = new LiberalStomp($this->server);

            if ($this->con->connect($this->username, $this->password)) {
                $this->_log(LOG_INFO, "Connected.");
            } else {
                $this->_log(LOG_ERR, 'Failed to connect to queue server');
                throw new ServerException('Failed to connect to queue server');
            }
        }
    }

    /**
     * Subscribe to all enabled notice queues for the current site.
     */
    protected function doSubscribe()
    {
        $this->_connect();
        foreach ($this->getQueues() as $queue) {
            $rawqueue = $this->queueName($queue);
            $this->_log(LOG_INFO, "Subscribing to $rawqueue");
            $this->con->subscribe($rawqueue);
        }
    }
    
    /**
     * Subscribe from all enabled notice queues for the current site.
     */
    protected function doUnsubscribe()
    {
        $this->_connect();
        foreach ($this->getQueues() as $queue) {
            $this->con->unsubscribe($this->queueName($queue));
        }
    }

    /**
     * Handle and acknowledge an event that's come in through a queue.
     *
     * If the queue handler reports failure, the message is requeued for later.
     * Missing notices or handler classes will drop the message.
     *
     * Side effects: in multi-site mode, may reset site configuration to
     * match the site that queued the event.
     *
     * @param StompFrame $frame
     * @return bool
     */
    protected function _handleItem($frame)
    {
        list($site, $queue) = $this->parseDestination($frame->headers['destination']);
        if ($site != common_config('site', 'server')) {
            $this->stats('switch');
            StatusNet::init($site);
        }

        if (is_numeric($frame->body)) {
            $id = intval($frame->body);
            $info = "notice $id posted at {$frame->headers['created']} in queue $queue";

            $notice = Notice::staticGet('id', $id);
            if (empty($notice)) {
                $this->_log(LOG_WARNING, "Skipping missing $info");
                $this->ack($frame);
                $this->commit();
                $this->begin();
                $this->stats('badnotice', $queue);
                return false;
            }

            $item = $notice;
        } else {
            // @fixme should we serialize, or json, or what here?
            $info = "string posted at {$frame->headers['created']} in queue $queue";
            $item = $frame->body;
        }

        $handler = $this->getHandler($queue);
        if (!$handler) {
            $this->_log(LOG_ERROR, "Missing handler class; skipping $info");
            $this->ack($frame);
            $this->commit();
            $this->begin();
            $this->stats('badhandler', $queue);
            return false;
        }

        $ok = $handler->handle($item);

        if (!$ok) {
            $this->_log(LOG_WARNING, "Failed handling $info");
            // FIXME we probably shouldn't have to do
            // this kind of queue management ourselves;
            // if we don't ack, it should resend...
            $this->ack($frame);
            $this->enqueue($item, $queue);
            $this->commit();
            $this->begin();
            $this->stats('requeued', $queue);
            return false;
        }

        $this->_log(LOG_INFO, "Successfully handled $info");
        $this->ack($frame);
        $this->commit();
        $this->begin();
        $this->stats('handled', $queue);
        return true;
    }

    /**
     * Combines the queue_basename from configuration with the
     * site server name and queue name to give eg:
     *
     * /queue/statusnet/identi.ca/sms
     *
     * @param string $queue
     * @return string
     */
    protected function queueName($queue)
    {
        return common_config('queue', 'queue_basename') .
            common_config('site', 'server') . '/' . $queue;
    }

    /**
     * Returns the site and queue name from the server-side queue.
     *
     * @param string queue destination (eg '/queue/statusnet/identi.ca/sms')
     * @return array of site and queue: ('identi.ca','sms') or false if unrecognized
     */
    protected function parseDestination($dest)
    {
        $prefix = common_config('queue', 'queue_basename');
        if (substr($dest, 0, strlen($prefix)) == $prefix) {
            $rest = substr($dest, strlen($prefix));
            return explode("/", $rest, 2);
        } else {
            common_log(LOG_ERR, "Got a message from unrecognized stomp queue: $dest");
            return array(false, false);
        }
    }

    function _log($level, $msg)
    {
        common_log($level, 'StompQueueManager: '.$msg);
    }

    protected function begin()
    {
        if ($this->useTransactions) {
            if ($this->transaction) {
                throw new Exception("Tried to start transaction in the middle of a transaction");
            }
            $this->transactionCount++;
            $this->transaction = $this->master->id . '-' . $this->transactionCount . '-' . time();
            $this->con->begin($this->transaction);
        }
    }

    protected function ack($frame)
    {
        if ($this->useTransactions) {
            if (!$this->transaction) {
                throw new Exception("Tried to ack but not in a transaction");
            }
        }
        $this->con->ack($frame, $this->transaction);
    }

    protected function commit()
    {
        if ($this->useTransactions) {
            if (!$this->transaction) {
                throw new Exception("Tried to commit but not in a transaction");
            }
            $this->con->commit($this->transaction);
            $this->transaction = null;
        }
    }

    protected function rollback()
    {
        if ($this->useTransactions) {
            if (!$this->transaction) {
                throw new Exception("Tried to rollback but not in a transaction");
            }
            $this->con->commit($this->transaction);
            $this->transaction = null;
        }
    }
}