]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/stompqueuemanager.php
19e8c49b5ce9c9e7a996ef3f8d948a9360b8f952
[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     protected $control;
42     
43     protected $sites = array();
44     protected $subscriptions = array();
45
46     protected $useTransactions = true;
47     protected $transaction = null;
48     protected $transactionCount = 0;
49
50     function __construct()
51     {
52         parent::__construct();
53         $this->server   = common_config('queue', 'stomp_server');
54         $this->username = common_config('queue', 'stomp_username');
55         $this->password = common_config('queue', 'stomp_password');
56         $this->base     = common_config('queue', 'queue_basename');
57         $this->control  = common_config('queue', 'control_channel');
58     }
59
60     /**
61      * Tell the i/o master we only need a single instance to cover
62      * all sites running in this process.
63      */
64     public static function multiSite()
65     {
66         return IoManager::INSTANCE_PER_PROCESS;
67     }
68
69     /**
70      * Record each site we'll be handling input for in this process,
71      * so we can listen to the necessary queues for it.
72      *
73      * @fixme possibly actually do subscription here to save another
74      *        loop over all sites later?
75      * @fixme possibly don't assume it's the current site
76      */
77     public function addSite($server)
78     {
79         $this->sites[] = $server;
80         $this->initialize();
81     }
82
83     /**
84      * Optional; ping any running queue handler daemons with a notification
85      * such as announcing a new site to handle or requesting clean shutdown.
86      * This avoids having to restart all the daemons manually to update configs
87      * and such.
88      *
89      * Currently only relevant for multi-site queue managers such as Stomp.
90      *
91      * @param string $event event key
92      * @param string $param optional parameter to append to key
93      * @return boolean success
94      */
95     public function sendControlSignal($event, $param='')
96     {
97         $message = $event;
98         if ($param != '') {
99             $message .= ':' . $param;
100         }
101         $this->_connect();
102         $result = $this->con->send($this->control,
103                                    $message,
104                                    array ('created' => common_sql_now()));
105         if ($result) {
106             $this->_log(LOG_INFO, "Sent control ping to queue daemons: $message");
107             return true;
108         } else {
109             $this->_log(LOG_ERR, "Failed sending control ping to queue daemons: $message");
110             return false;
111         }
112     }
113
114     /**
115      * Instantiate the appropriate QueueHandler class for the given queue.
116      *
117      * @param string $queue
118      * @return mixed QueueHandler or null
119      */
120     function getHandler($queue)
121     {
122         $handlers = $this->handlers[$this->currentSite()];
123         if (isset($handlers[$queue])) {
124             $class = $handlers[$queue];
125             if (class_exists($class)) {
126                 return new $class();
127             } else {
128                 common_log(LOG_ERR, "Nonexistent handler class '$class' for queue '$queue'");
129             }
130         } else {
131             common_log(LOG_ERR, "Requested handler for unkown queue '$queue'");
132         }
133         return null;
134     }
135
136     /**
137      * Get a list of all registered queue transport names.
138      *
139      * @return array of strings
140      */
141     function getQueues()
142     {
143         $group = $this->activeGroup();
144         $site = $this->currentSite();
145         if (empty($this->groups[$site][$group])) {
146             return array();
147         } else {
148             return array_keys($this->groups[$site][$group]);
149         }
150     }
151
152     /**
153      * Register a queue transport name and handler class for your plugin.
154      * Only registered transports will be reliably picked up!
155      *
156      * @param string $transport
157      * @param string $class
158      * @param string $group
159      */
160     public function connect($transport, $class, $group='queuedaemon')
161     {
162         $this->handlers[$this->currentSite()][$transport] = $class;
163         $this->groups[$this->currentSite()][$group][$transport] = $class;
164     }
165
166     /**
167      * Saves a notice object reference into the queue item table.
168      * @return boolean true on success
169      */
170     public function enqueue($object, $queue)
171     {
172         $msg = $this->encode($object);
173         $rep = $this->logrep($object);
174
175         $this->_connect();
176
177         // XXX: serialize and send entire notice
178
179         $result = $this->con->send($this->queueName($queue),
180                                    $msg,                // BODY of the message
181                                    array ('created' => common_sql_now(),
182                                           'persistent' => 'true'));
183
184         if (!$result) {
185             common_log(LOG_ERR, "Error sending $rep to $queue queue");
186             return false;
187         }
188
189         common_log(LOG_DEBUG, "complete remote queueing $rep for $queue");
190         $this->stats('enqueued', $queue);
191     }
192
193     /**
194      * Send any sockets we're listening on to the IO manager
195      * to wait for input.
196      *
197      * @return array of resources
198      */
199     public function getSockets()
200     {
201         return array($this->con->getSocket());
202     }
203
204     /**
205      * We've got input to handle on our socket!
206      * Read any waiting Stomp frame(s) and process them.
207      *
208      * @param resource $socket
209      * @return boolean ok on success
210      */
211     public function handleInput($socket)
212     {
213         assert($socket === $this->con->getSocket());
214         $ok = true;
215         $frames = $this->con->readFrames();
216         foreach ($frames as $frame) {
217             $dest = $frame->headers['destination'];
218             if ($dest == $this->control) {
219                 if (!$this->handleControlSignal($frame)) {
220                     // We got a control event that requests a shutdown;
221                     // close out and stop handling anything else!
222                     break;
223                 }
224             } else {
225                 $ok = $ok && $this->handleItem($frame);
226             }
227         }
228         return $ok;
229     }
230
231     /**
232      * Initialize our connection and subscribe to all the queues
233      * we're going to need to handle...
234      *
235      * Side effects: in multi-site mode, may reset site configuration.
236      *
237      * @param IoMaster $master process/event controller
238      * @return bool return false on failure
239      */
240     public function start($master)
241     {
242         parent::start($master);
243         $this->_connect();
244
245         $this->con->subscribe($this->control);
246         if ($this->sites) {
247             foreach ($this->sites as $server) {
248                 StatusNet::init($server);
249                 $this->doSubscribe();
250             }
251         } else {
252             $this->doSubscribe();
253         }
254         $this->begin();
255         return true;
256     }
257     
258     /**
259      * Subscribe to all the queues we're going to need to handle...
260      *
261      * Side effects: in multi-site mode, may reset site configuration.
262      *
263      * @return bool return false on failure
264      */
265     public function finish()
266     {
267         // If there are any outstanding delivered messages we haven't processed,
268         // free them for another thread to take.
269         $this->rollback();
270         $this->con->unsubscribe($this->control);
271         if ($this->sites) {
272             foreach ($this->sites as $server) {
273                 StatusNet::init($server);
274                 $this->doUnsubscribe();
275             }
276         } else {
277             $this->doUnsubscribe();
278         }
279         return true;
280     }
281
282     /**
283      * Get identifier of the currently active site configuration
284      * @return string
285      */
286     protected function currentSite()
287     {
288         return common_config('site', 'server'); // @fixme switch to nickname
289     }
290
291     /**
292      * Lazy open connection to Stomp queue server.
293      */
294     protected function _connect()
295     {
296         if (empty($this->con)) {
297             $this->_log(LOG_INFO, "Connecting to '$this->server' as '$this->username'...");
298             $this->con = new LiberalStomp($this->server);
299
300             if ($this->con->connect($this->username, $this->password)) {
301                 $this->_log(LOG_INFO, "Connected.");
302             } else {
303                 $this->_log(LOG_ERR, 'Failed to connect to queue server');
304                 throw new ServerException('Failed to connect to queue server');
305             }
306         }
307     }
308
309     /**
310      * Subscribe to all enabled notice queues for the current site.
311      */
312     protected function doSubscribe()
313     {
314         $site = $this->currentSite();
315         $this->_connect();
316         foreach ($this->getQueues() as $queue) {
317             $rawqueue = $this->queueName($queue);
318             $this->subscriptions[$site][$queue] = $rawqueue;
319             $this->_log(LOG_INFO, "Subscribing to $rawqueue");
320             $this->con->subscribe($rawqueue);
321         }
322     }
323
324     /**
325      * Subscribe from all enabled notice queues for the current site.
326      */
327     protected function doUnsubscribe()
328     {
329         $site = $this->currentSite();
330         $this->_connect();
331         if (!empty($this->subscriptions[$site])) {
332             foreach ($this->subscriptions[$site] as $queue => $rawqueue) {
333                 $this->_log(LOG_INFO, "Unsubscribing from $rawqueue");
334                 $this->con->unsubscribe($rawqueue);
335                 unset($this->subscriptions[$site][$queue]);
336             }
337         }
338     }
339
340     /**
341      * Handle and acknowledge an event that's come in through a queue.
342      *
343      * If the queue handler reports failure, the message is requeued for later.
344      * Missing notices or handler classes will drop the message.
345      *
346      * Side effects: in multi-site mode, may reset site configuration to
347      * match the site that queued the event.
348      *
349      * @param StompFrame $frame
350      * @return bool
351      */
352     protected function handleItem($frame)
353     {
354         list($site, $queue) = $this->parseDestination($frame->headers['destination']);
355         if ($site != $this->currentSite()) {
356             $this->stats('switch');
357             StatusNet::init($site);
358         }
359
360         if (is_numeric($frame->body)) {
361             $id = intval($frame->body);
362             $info = "notice $id posted at {$frame->headers['created']} in queue $queue";
363
364             $notice = Notice::staticGet('id', $id);
365             if (empty($notice)) {
366                 $this->_log(LOG_WARNING, "Skipping missing $info");
367                 $this->ack($frame);
368                 $this->commit();
369                 $this->begin();
370                 $this->stats('badnotice', $queue);
371                 return false;
372             }
373
374             $item = $notice;
375         } else {
376             // @fixme should we serialize, or json, or what here?
377             $info = "string posted at {$frame->headers['created']} in queue $queue";
378             $item = $frame->body;
379         }
380
381         $handler = $this->getHandler($queue);
382         if (!$handler) {
383             $this->_log(LOG_ERR, "Missing handler class; skipping $info");
384             $this->ack($frame);
385             $this->commit();
386             $this->begin();
387             $this->stats('badhandler', $queue);
388             return false;
389         }
390
391         $ok = $handler->handle($item);
392
393         if (!$ok) {
394             $this->_log(LOG_WARNING, "Failed handling $info");
395             // FIXME we probably shouldn't have to do
396             // this kind of queue management ourselves;
397             // if we don't ack, it should resend...
398             $this->ack($frame);
399             $this->enqueue($item, $queue);
400             $this->commit();
401             $this->begin();
402             $this->stats('requeued', $queue);
403             return false;
404         }
405
406         $this->_log(LOG_INFO, "Successfully handled $info");
407         $this->ack($frame);
408         $this->commit();
409         $this->begin();
410         $this->stats('handled', $queue);
411         return true;
412     }
413
414     /**
415      * Process a control signal broadcast.
416      *
417      * @param array $frame Stomp frame
418      * @return bool true to continue; false to stop further processing.
419      */
420     protected function handleControlSignal($frame)
421     {
422         $message = trim($frame->body);
423         if (strpos($message, ':') !== false) {
424             list($event, $param) = explode(':', $message, 2);
425         } else {
426             $event = $message;
427             $param = '';
428         }
429
430         $shutdown = false;
431
432         if ($event == 'shutdown') {
433             $this->master->requestShutdown();
434             $shutdown = true;
435         } else if ($event == 'restart') {
436             $this->master->requestRestart();
437             $shutdown = true;
438         } else if ($event == 'update') {
439             $this->updateSiteConfig($param);
440         } else {
441             $this->_log(LOG_ERR, "Ignoring unrecognized control message: $message");
442         }
443
444         $this->ack($frame);
445         $this->commit();
446         $this->begin();
447         return $shutdown;
448     }
449     
450     /**
451      * Set us up with queue subscriptions for a new site added at runtime,
452      * triggered by a broadcast to the 'statusnet-control' topic.
453      *
454      * @param array $frame Stomp frame
455      * @return bool true to continue; false to stop further processing.
456      */
457     protected function updateSiteConfig($nickname)
458     {
459         if (empty($this->sites)) {
460             if ($nickname == common_config('site', 'nickname')) {
461                 StatusNet::init(common_config('site', 'server'));
462                 $this->doUnsubscribe();
463                 $this->doSubscribe();
464             } else {
465                 $this->_log(LOG_INFO, "Ignoring update ping for other site $nickname");
466             }
467         } else {
468             $sn = Status_network::staticGet($nickname);
469             if ($sn) {
470                 $server = $sn->getServerName(); // @fixme do config-by-nick
471                 StatusNet::init($server);
472                 if (empty($this->sites[$server])) {
473                     $this->addSite($server);
474                 }
475                 $this->_log(LOG_INFO, "(Re)subscribing to queues for site $nickname / $server");
476                 $this->doUnsubscribe();
477                 $this->doSubscribe();
478                 $this->stats('siteupdate');
479             } else {
480                 $this->_log(LOG_ERR, "Ignoring ping for unrecognized new site $nickname");
481             }
482         }
483     }
484
485     /**
486      * Combines the queue_basename from configuration with the
487      * site server name and queue name to give eg:
488      *
489      * /queue/statusnet/identi.ca/sms
490      *
491      * @param string $queue
492      * @return string
493      */
494     protected function queueName($queue)
495     {
496         return common_config('queue', 'queue_basename') .
497             $this->currentSite() . '/' . $queue;
498     }
499
500     /**
501      * Returns the site and queue name from the server-side queue.
502      *
503      * @param string queue destination (eg '/queue/statusnet/identi.ca/sms')
504      * @return array of site and queue: ('identi.ca','sms') or false if unrecognized
505      */
506     protected function parseDestination($dest)
507     {
508         $prefix = common_config('queue', 'queue_basename');
509         if (substr($dest, 0, strlen($prefix)) == $prefix) {
510             $rest = substr($dest, strlen($prefix));
511             return explode("/", $rest, 2);
512         } else {
513             common_log(LOG_ERR, "Got a message from unrecognized stomp queue: $dest");
514             return array(false, false);
515         }
516     }
517
518     function _log($level, $msg)
519     {
520         common_log($level, 'StompQueueManager: '.$msg);
521     }
522
523     protected function begin()
524     {
525         if ($this->useTransactions) {
526             if ($this->transaction) {
527                 throw new Exception("Tried to start transaction in the middle of a transaction");
528             }
529             $this->transactionCount++;
530             $this->transaction = $this->master->id . '-' . $this->transactionCount . '-' . time();
531             $this->con->begin($this->transaction);
532         }
533     }
534
535     protected function ack($frame)
536     {
537         if ($this->useTransactions) {
538             if (!$this->transaction) {
539                 throw new Exception("Tried to ack but not in a transaction");
540             }
541         }
542         $this->con->ack($frame, $this->transaction);
543     }
544
545     protected function commit()
546     {
547         if ($this->useTransactions) {
548             if (!$this->transaction) {
549                 throw new Exception("Tried to commit but not in a transaction");
550             }
551             $this->con->commit($this->transaction);
552             $this->transaction = null;
553         }
554     }
555
556     protected function rollback()
557     {
558         if ($this->useTransactions) {
559             if (!$this->transaction) {
560                 throw new Exception("Tried to rollback but not in a transaction");
561             }
562             $this->con->commit($this->transaction);
563             $this->transaction = null;
564         }
565     }
566 }
567