]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/stompqueuemanager.php
8f0091a1384f51b1cf07ad6c4bddf7dfbd920f03
[quix0rs-gnu-social.git] / lib / stompqueuemanager.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Abstract class for queue managers
6  *
7  * PHP version 5
8  *
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.
13  *
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.
18  *
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/>.
21  *
22  * @category  QueueManager
23  * @package   StatusNet
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/
29  */
30
31 require_once 'Stomp.php';
32
33
34 class StompQueueManager extends QueueManager
35 {
36     var $server = null;
37     var $username = null;
38     var $password = null;
39     var $base = null;
40     var $con = null;
41     
42     protected $sites = array();
43
44     protected $useTransactions = true;
45     protected $transaction = null;
46     protected $transactionCount = 0;
47
48     function __construct()
49     {
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');
55     }
56
57     /**
58      * Tell the i/o master we only need a single instance to cover
59      * all sites running in this process.
60      */
61     public static function multiSite()
62     {
63         return IoManager::INSTANCE_PER_PROCESS;
64     }
65
66     /**
67      * Record each site we'll be handling input for in this process,
68      * so we can listen to the necessary queues for it.
69      *
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
73      */
74     public function addSite($server)
75     {
76         $this->sites[] = $server;
77         $this->initialize();
78     }
79
80
81     /**
82      * Instantiate the appropriate QueueHandler class for the given queue.
83      *
84      * @param string $queue
85      * @return mixed QueueHandler or null
86      */
87     function getHandler($queue)
88     {
89         $handlers = $this->handlers[common_config('site', 'server')];
90         if (isset($handlers[$queue])) {
91             $class = $handlers[$queue];
92             if (class_exists($class)) {
93                 return new $class();
94             } else {
95                 common_log(LOG_ERR, "Nonexistent handler class '$class' for queue '$queue'");
96             }
97         } else {
98             common_log(LOG_ERR, "Requested handler for unkown queue '$queue'");
99         }
100         return null;
101     }
102
103     /**
104      * Get a list of all registered queue transport names.
105      *
106      * @return array of strings
107      */
108     function getQueues()
109     {
110         $group = $this->activeGroup();
111         $site = common_config('site', 'server');
112         if (empty($this->groups[$site][$group])) {
113             return array();
114         } else {
115             return array_keys($this->groups[$site][$group]);
116         }
117     }
118
119     /**
120      * Register a queue transport name and handler class for your plugin.
121      * Only registered transports will be reliably picked up!
122      *
123      * @param string $transport
124      * @param string $class
125      * @param string $group
126      */
127     public function connect($transport, $class, $group='queuedaemon')
128     {
129         $this->handlers[common_config('site', 'server')][$transport] = $class;
130         $this->groups[common_config('site', 'server')][$group][$transport] = $class;
131     }
132
133     /**
134      * Saves a notice object reference into the queue item table.
135      * @return boolean true on success
136      */
137     public function enqueue($object, $queue)
138     {
139         $msg = $this->encode($object);
140         $rep = $this->logrep($object);
141
142         $this->_connect();
143
144         // XXX: serialize and send entire notice
145
146         $result = $this->con->send($this->queueName($queue),
147                                    $msg,                // BODY of the message
148                                    array ('created' => common_sql_now()));
149
150         if (!$result) {
151             common_log(LOG_ERR, "Error sending $rep to $queue queue");
152             return false;
153         }
154
155         common_log(LOG_DEBUG, "complete remote queueing $rep for $queue");
156         $this->stats('enqueued', $queue);
157     }
158
159     /**
160      * Send any sockets we're listening on to the IO manager
161      * to wait for input.
162      *
163      * @return array of resources
164      */
165     public function getSockets()
166     {
167         return array($this->con->getSocket());
168     }
169
170     /**
171      * We've got input to handle on our socket!
172      * Read any waiting Stomp frame(s) and process them.
173      *
174      * @param resource $socket
175      * @return boolean ok on success
176      */
177     public function handleInput($socket)
178     {
179         assert($socket === $this->con->getSocket());
180         $ok = true;
181         $frames = $this->con->readFrames();
182         foreach ($frames as $frame) {
183             $ok = $ok && $this->_handleItem($frame);
184         }
185         return $ok;
186     }
187
188     /**
189      * Initialize our connection and subscribe to all the queues
190      * we're going to need to handle...
191      *
192      * Side effects: in multi-site mode, may reset site configuration.
193      *
194      * @param IoMaster $master process/event controller
195      * @return bool return false on failure
196      */
197     public function start($master)
198     {
199         parent::start($master);
200         if ($this->sites) {
201             foreach ($this->sites as $server) {
202                 StatusNet::init($server);
203                 $this->doSubscribe();
204             }
205         } else {
206             $this->doSubscribe();
207         }
208         $this->begin();
209         return true;
210     }
211     
212     /**
213      * Subscribe to all the queues we're going to need to handle...
214      *
215      * Side effects: in multi-site mode, may reset site configuration.
216      *
217      * @return bool return false on failure
218      */
219     public function finish()
220     {
221         // If there are any outstanding delivered messages we haven't processed,
222         // free them for another thread to take.
223         $this->rollback();
224         if ($this->sites) {
225             foreach ($this->sites as $server) {
226                 StatusNet::init($server);
227                 $this->doUnsubscribe();
228             }
229         } else {
230             $this->doUnsubscribe();
231         }
232         return true;
233     }
234     
235     /**
236      * Lazy open connection to Stomp queue server.
237      */
238     protected function _connect()
239     {
240         if (empty($this->con)) {
241             $this->_log(LOG_INFO, "Connecting to '$this->server' as '$this->username'...");
242             $this->con = new LiberalStomp($this->server);
243
244             if ($this->con->connect($this->username, $this->password)) {
245                 $this->_log(LOG_INFO, "Connected.");
246             } else {
247                 $this->_log(LOG_ERR, 'Failed to connect to queue server');
248                 throw new ServerException('Failed to connect to queue server');
249             }
250         }
251     }
252
253     /**
254      * Subscribe to all enabled notice queues for the current site.
255      */
256     protected function doSubscribe()
257     {
258         $this->_connect();
259         foreach ($this->getQueues() as $queue) {
260             $rawqueue = $this->queueName($queue);
261             $this->_log(LOG_INFO, "Subscribing to $rawqueue");
262             $this->con->subscribe($rawqueue);
263         }
264     }
265     
266     /**
267      * Subscribe from all enabled notice queues for the current site.
268      */
269     protected function doUnsubscribe()
270     {
271         $this->_connect();
272         foreach ($this->getQueues() as $queue) {
273             $this->con->unsubscribe($this->queueName($queue));
274         }
275     }
276
277     /**
278      * Handle and acknowledge an event that's come in through a queue.
279      *
280      * If the queue handler reports failure, the message is requeued for later.
281      * Missing notices or handler classes will drop the message.
282      *
283      * Side effects: in multi-site mode, may reset site configuration to
284      * match the site that queued the event.
285      *
286      * @param StompFrame $frame
287      * @return bool
288      */
289     protected function _handleItem($frame)
290     {
291         list($site, $queue) = $this->parseDestination($frame->headers['destination']);
292         if ($site != common_config('site', 'server')) {
293             $this->stats('switch');
294             StatusNet::init($site);
295         }
296
297         if (is_numeric($frame->body)) {
298             $id = intval($frame->body);
299             $info = "notice $id posted at {$frame->headers['created']} in queue $queue";
300
301             $notice = Notice::staticGet('id', $id);
302             if (empty($notice)) {
303                 $this->_log(LOG_WARNING, "Skipping missing $info");
304                 $this->ack($frame);
305                 $this->commit();
306                 $this->begin();
307                 $this->stats('badnotice', $queue);
308                 return false;
309             }
310
311             $item = $notice;
312         } else {
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;
316         }
317
318         $handler = $this->getHandler($queue);
319         if (!$handler) {
320             $this->_log(LOG_ERROR, "Missing handler class; skipping $info");
321             $this->ack($frame);
322             $this->commit();
323             $this->begin();
324             $this->stats('badhandler', $queue);
325             return false;
326         }
327
328         $ok = $handler->handle($item);
329
330         if (!$ok) {
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...
335             $this->ack($frame);
336             $this->enqueue($item, $queue);
337             $this->commit();
338             $this->begin();
339             $this->stats('requeued', $queue);
340             return false;
341         }
342
343         $this->_log(LOG_INFO, "Successfully handled $info");
344         $this->ack($frame);
345         $this->commit();
346         $this->begin();
347         $this->stats('handled', $queue);
348         return true;
349     }
350
351     /**
352      * Combines the queue_basename from configuration with the
353      * site server name and queue name to give eg:
354      *
355      * /queue/statusnet/identi.ca/sms
356      *
357      * @param string $queue
358      * @return string
359      */
360     protected function queueName($queue)
361     {
362         return common_config('queue', 'queue_basename') .
363             common_config('site', 'server') . '/' . $queue;
364     }
365
366     /**
367      * Returns the site and queue name from the server-side queue.
368      *
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
371      */
372     protected function parseDestination($dest)
373     {
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);
378         } else {
379             common_log(LOG_ERR, "Got a message from unrecognized stomp queue: $dest");
380             return array(false, false);
381         }
382     }
383
384     function _log($level, $msg)
385     {
386         common_log($level, 'StompQueueManager: '.$msg);
387     }
388
389     protected function begin()
390     {
391         if ($this->useTransactions) {
392             if ($this->transaction) {
393                 throw new Exception("Tried to start transaction in the middle of a transaction");
394             }
395             $this->transactionCount++;
396             $this->transaction = $this->master->id . '-' . $this->transactionCount . '-' . time();
397             $this->con->begin($this->transaction);
398         }
399     }
400
401     protected function ack($frame)
402     {
403         if ($this->useTransactions) {
404             if (!$this->transaction) {
405                 throw new Exception("Tried to ack but not in a transaction");
406             }
407         }
408         $this->con->ack($frame, $this->transaction);
409     }
410
411     protected function commit()
412     {
413         if ($this->useTransactions) {
414             if (!$this->transaction) {
415                 throw new Exception("Tried to commit but not in a transaction");
416             }
417             $this->con->commit($this->transaction);
418             $this->transaction = null;
419         }
420     }
421
422     protected function rollback()
423     {
424         if ($this->useTransactions) {
425             if (!$this->transaction) {
426                 throw new Exception("Tried to rollback but not in a transaction");
427             }
428             $this->con->commit($this->transaction);
429             $this->transaction = null;
430         }
431     }
432 }
433