]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/stompqueuemanager.php
Merge branch 'testing' of git@gitorious.org:statusnet/mainline into 0.9.x
[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 require_once 'Stomp/Exception.php';
33
34 class StompQueueManager extends QueueManager
35 {
36     protected $servers;
37     protected $username;
38     protected $password;
39     protected $base;
40     protected $control;
41
42     protected $useTransactions = true;
43
44     protected $sites = array();
45     protected $subscriptions = array();
46
47     protected $cons = array(); // all open connections
48     protected $disconnect = array();
49     protected $transaction = array();
50     protected $transactionCount = array();
51     protected $defaultIdx = 0;
52
53     function __construct()
54     {
55         parent::__construct();
56         $server = common_config('queue', 'stomp_server');
57         if (is_array($server)) {
58             $this->servers = $server;
59         } else {
60             $this->servers = array($server);
61         }
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     }
67
68     /**
69      * Tell the i/o master we only need a single instance to cover
70      * all sites running in this process.
71      */
72     public static function multiSite()
73     {
74         return IoManager::INSTANCE_PER_PROCESS;
75     }
76
77     /**
78      * Record each site we'll be handling input for in this process,
79      * so we can listen to the necessary queues for it.
80      *
81      * @fixme possibly actually do subscription here to save another
82      *        loop over all sites later?
83      * @fixme possibly don't assume it's the current site
84      */
85     public function addSite($server)
86     {
87         $this->sites[] = $server;
88         $this->initialize();
89     }
90
91     /**
92      * Optional; ping any running queue handler daemons with a notification
93      * such as announcing a new site to handle or requesting clean shutdown.
94      * This avoids having to restart all the daemons manually to update configs
95      * and such.
96      *
97      * Currently only relevant for multi-site queue managers such as Stomp.
98      *
99      * @param string $event event key
100      * @param string $param optional parameter to append to key
101      * @return boolean success
102      */
103     public function sendControlSignal($event, $param='')
104     {
105         $message = $event;
106         if ($param != '') {
107             $message .= ':' . $param;
108         }
109         $this->_connect();
110         $result = $this->_send($this->control,
111                                $message,
112                                array ('created' => common_sql_now()));
113         if ($result) {
114             $this->_log(LOG_INFO, "Sent control ping to queue daemons: $message");
115             return true;
116         } else {
117             $this->_log(LOG_ERR, "Failed sending control ping to queue daemons: $message");
118             return false;
119         }
120     }
121
122     /**
123      * Instantiate the appropriate QueueHandler class for the given queue.
124      *
125      * @param string $queue
126      * @return mixed QueueHandler or null
127      */
128     function getHandler($queue)
129     {
130         $handlers = $this->handlers[$this->currentSite()];
131         if (isset($handlers[$queue])) {
132             $class = $handlers[$queue];
133             if (class_exists($class)) {
134                 return new $class();
135             } else {
136                 common_log(LOG_ERR, "Nonexistent handler class '$class' for queue '$queue'");
137             }
138         } else {
139             common_log(LOG_ERR, "Requested handler for unkown queue '$queue'");
140         }
141         return null;
142     }
143
144     /**
145      * Get a list of all registered queue transport names.
146      *
147      * @return array of strings
148      */
149     function getQueues()
150     {
151         $group = $this->activeGroup();
152         $site = $this->currentSite();
153         if (empty($this->groups[$site][$group])) {
154             return array();
155         } else {
156             return array_keys($this->groups[$site][$group]);
157         }
158     }
159
160     /**
161      * Register a queue transport name and handler class for your plugin.
162      * Only registered transports will be reliably picked up!
163      *
164      * @param string $transport
165      * @param string $class
166      * @param string $group
167      */
168     public function connect($transport, $class, $group='queuedaemon')
169     {
170         $this->handlers[$this->currentSite()][$transport] = $class;
171         $this->groups[$this->currentSite()][$group][$transport] = $class;
172     }
173
174     /**
175      * Saves a notice object reference into the queue item table.
176      * @return boolean true on success
177      * @throws StompException on connection or send error
178      */
179     public function enqueue($object, $queue)
180     {
181         $this->_connect();
182         return $this->_doEnqueue($object, $queue, $this->defaultIdx);
183     }
184
185     /**
186      * Saves a notice object reference into the queue item table
187      * on the given connection.
188      *
189      * @return boolean true on success
190      * @throws StompException on connection or send error
191      */
192     protected function _doEnqueue($object, $queue, $idx)
193     {
194         $msg = $this->encode($object);
195         $rep = $this->logrep($object);
196
197         $props = array('created' => common_sql_now());
198         if ($this->isPersistent($queue)) {
199             $props['persistent'] = 'true';
200         }
201
202         $con = $this->cons[$idx];
203         $host = $con->getServer();
204         $result = $con->send($this->queueName($queue), $msg, $props);
205
206         if (!$result) {
207             common_log(LOG_ERR, "Error sending $rep to $queue queue on $host");
208             return false;
209         }
210
211         common_log(LOG_DEBUG, "complete remote queueing $rep for $queue on $host");
212         $this->stats('enqueued', $queue);
213         return true;
214     }
215
216     /**
217      * Determine whether messages to this queue should be marked as persistent.
218      * Actual persistent storage depends on the queue server's configuration.
219      * @param string $queue
220      * @return bool
221      */
222     protected function isPersistent($queue)
223     {
224         $mode = common_config('queue', 'stomp_persistent');
225         if (is_array($mode)) {
226             return in_array($queue, $mode);
227         } else {
228             return (bool)$mode;
229         }
230     }
231
232     /**
233      * Send any sockets we're listening on to the IO manager
234      * to wait for input.
235      *
236      * @return array of resources
237      */
238     public function getSockets()
239     {
240         $sockets = array();
241         foreach ($this->cons as $con) {
242             if ($con) {
243                 $sockets[] = $con->getSocket();
244             }
245         }
246         return $sockets;
247     }
248
249     /**
250      * Get the Stomp connection object associated with the given socket.
251      * @param resource $socket
252      * @return int index into connections list
253      * @throws Exception
254      */
255     protected function connectionFromSocket($socket)
256     {
257         foreach ($this->cons as $i => $con) {
258             if ($con && $con->getSocket() === $socket) {
259                 return $i;
260             }
261         }
262         throw new Exception(__CLASS__ . " asked to read from unrecognized socket");
263     }
264
265     /**
266      * We've got input to handle on our socket!
267      * Read any waiting Stomp frame(s) and process them.
268      *
269      * @param resource $socket
270      * @return boolean ok on success
271      */
272     public function handleInput($socket)
273     {
274         $idx = $this->connectionFromSocket($socket);
275         $con = $this->cons[$idx];
276         $host = $con->getServer();
277
278         $ok = true;
279         try {
280             $frames = $con->readFrames();
281         } catch (StompException $e) {
282             common_log(LOG_ERR, "Lost connection to $host: " . $e->getMessage());
283             $this->cons[$idx] = null;
284             $this->transaction[$idx] = null;
285             $this->disconnect[$idx] = time();
286             return false;
287         }
288         foreach ($frames as $frame) {
289             $dest = $frame->headers['destination'];
290             if ($dest == $this->control) {
291                 if (!$this->handleControlSignal($idx, $frame)) {
292                     // We got a control event that requests a shutdown;
293                     // close out and stop handling anything else!
294                     break;
295                 }
296             } else {
297                 $ok = $ok && $this->handleItem($idx, $frame);
298             }
299         }
300         return $ok;
301     }
302
303     /**
304      * Attempt to reconnect in background if we lost a connection.
305      */
306     function idle()
307     {
308         $now = time();
309         foreach ($this->cons as $idx => $con) {
310             if (empty($con)) {
311                 $age = $now - $this->disconnect[$idx];
312                 if ($age >= 60) {
313                     $this->_reconnect($idx);
314                 }
315             }
316         }
317         return true;
318     }
319
320     /**
321      * Initialize our connection and subscribe to all the queues
322      * we're going to need to handle... If multiple queue servers
323      * are configured for failover, we'll listen to all of them.
324      *
325      * Side effects: in multi-site mode, may reset site configuration.
326      *
327      * @param IoMaster $master process/event controller
328      * @return bool return false on failure
329      */
330     public function start($master)
331     {
332         parent::start($master);
333         $this->_connectAll();
334
335         common_log(LOG_INFO, "Subscribing to $this->control");
336         foreach ($this->cons as $con) {
337             if ($con) {
338                 $con->subscribe($this->control);
339             }
340         }
341         if ($this->sites) {
342             foreach ($this->sites as $server) {
343                 StatusNet::init($server);
344                 $this->doSubscribe();
345             }
346         } else {
347             $this->doSubscribe();
348         }
349         foreach ($this->cons as $i => $con) {
350             if ($con) {
351                 $this->begin($i);
352             }
353         }
354         return true;
355     }
356
357     /**
358      * Subscribe to all the queues we're going to need to handle...
359      *
360      * Side effects: in multi-site mode, may reset site configuration.
361      *
362      * @return bool return false on failure
363      */
364     public function finish()
365     {
366         // If there are any outstanding delivered messages we haven't processed,
367         // free them for another thread to take.
368         foreach ($this->cons as $i => $con) {
369             if ($con) {
370                 $this->rollback($i);
371                 $con->unsubscribe($this->control);
372             }
373         }
374         if ($this->sites) {
375             foreach ($this->sites as $server) {
376                 StatusNet::init($server);
377                 $this->doUnsubscribe();
378             }
379         } else {
380             $this->doUnsubscribe();
381         }
382         return true;
383     }
384
385     /**
386      * Get identifier of the currently active site configuration
387      * @return string
388      */
389     protected function currentSite()
390     {
391         return common_config('site', 'server'); // @fixme switch to nickname
392     }
393
394     /**
395      * Lazy open a single connection to Stomp queue server.
396      * If multiple servers are configured, we let the Stomp client library
397      * worry about finding a working connection among them.
398      */
399     protected function _connect()
400     {
401         if (empty($this->cons)) {
402             $list = $this->servers;
403             if (count($list) > 1) {
404                 shuffle($list); // Randomize to spread load
405                 $url = 'failover://(' . implode(',', $list) . ')';
406             } else {
407                 $url = $list[0];
408             }
409             $con = $this->_doConnect($url);
410             $this->cons = array($con);
411             $this->transactionCount = array(0);
412             $this->transaction = array(null);
413             $this->disconnect = array(null);
414         }
415     }
416
417     /**
418      * Lazy open connections to all Stomp servers, if in manual failover
419      * mode. This means the queue servers don't speak to each other, so
420      * we have to listen to all of them to make sure we get all events.
421      */
422     protected function _connectAll()
423     {
424         if (!common_config('queue', 'stomp_manual_failover')) {
425             return $this->_connect();
426         }
427         if (empty($this->cons)) {
428             $this->cons = array();
429             $this->transactionCount = array();
430             $this->transaction = array();
431             foreach ($this->servers as $idx => $server) {
432                 try {
433                     $this->cons[] = $this->_doConnect($server);
434                     $this->disconnect[] = null;
435                 } catch (Exception $e) {
436                     // s'okay, we'll live
437                     $this->cons[] = null;
438                     $this->disconnect[] = time();
439                 }
440                 $this->transactionCount[] = 0;
441                 $this->transaction[] = null;
442             }
443             if (empty($this->cons)) {
444                 throw new ServerException("No queue servers reachable...");
445                 return false;
446             }
447         }
448     }
449
450     protected function _reconnect($idx)
451     {
452         try {
453             $con = $this->_doConnect($this->servers[$idx]);
454         } catch (Exception $e) {
455             $this->_log(LOG_ERR, $e->getMessage());
456             $con = null;
457         }
458         if ($con) {
459             $this->cons[$idx] = $con;
460             $this->disconnect[$idx] = null;
461
462             // now we have to listen to everything...
463             // @fixme refactor this nicer. :P
464             $host = $con->getServer();
465             $this->_log(LOG_INFO, "Resubscribing to $this->control on $host");
466             $con->subscribe($this->control);
467             foreach ($this->subscriptions as $site => $queues) {
468                 foreach ($queues as $queue) {
469                     $this->_log(LOG_INFO, "Resubscribing to $queue on $host");
470                     $con->subscribe($queue);
471                 }
472             }
473             $this->begin($idx);
474         } else {
475             // Try again later...
476             $this->disconnect[$idx] = time();
477         }
478     }
479
480     protected function _doConnect($server)
481     {
482         $this->_log(LOG_INFO, "Connecting to '$server' as '$this->username'...");
483         $con = new LiberalStomp($server);
484
485         if ($con->connect($this->username, $this->password)) {
486             $this->_log(LOG_INFO, "Connected.");
487         } else {
488             $this->_log(LOG_ERR, 'Failed to connect to queue server');
489             throw new ServerException('Failed to connect to queue server');
490         }
491
492         return $con;
493     }
494
495     /**
496      * Subscribe to all enabled notice queues for the current site.
497      */
498     protected function doSubscribe()
499     {
500         $site = $this->currentSite();
501         $this->_connect();
502         foreach ($this->getQueues() as $queue) {
503             $rawqueue = $this->queueName($queue);
504             $this->subscriptions[$site][$queue] = $rawqueue;
505             $this->_log(LOG_INFO, "Subscribing to $rawqueue");
506             foreach ($this->cons as $con) {
507                 if ($con) {
508                     $con->subscribe($rawqueue);
509                 }
510             }
511         }
512     }
513
514     /**
515      * Subscribe from all enabled notice queues for the current site.
516      */
517     protected function doUnsubscribe()
518     {
519         $site = $this->currentSite();
520         $this->_connect();
521         if (!empty($this->subscriptions[$site])) {
522             foreach ($this->subscriptions[$site] as $queue => $rawqueue) {
523                 $this->_log(LOG_INFO, "Unsubscribing from $rawqueue");
524                 foreach ($this->cons as $con) {
525                     if ($con) {
526                         $con->unsubscribe($rawqueue);
527                     }
528                 }
529                 unset($this->subscriptions[$site][$queue]);
530             }
531         }
532     }
533
534     /**
535      * Handle and acknowledge an event that's come in through a queue.
536      *
537      * If the queue handler reports failure, the message is requeued for later.
538      * Missing notices or handler classes will drop the message.
539      *
540      * Side effects: in multi-site mode, may reset site configuration to
541      * match the site that queued the event.
542      *
543      * @param int $idx connection index
544      * @param StompFrame $frame
545      * @return bool
546      */
547     protected function handleItem($idx, $frame)
548     {
549         $this->defaultIdx = $idx;
550
551         list($site, $queue) = $this->parseDestination($frame->headers['destination']);
552         if ($site != $this->currentSite()) {
553             $this->stats('switch');
554             StatusNet::init($site);
555         }
556
557         $host = $this->cons[$idx]->getServer();
558         if (is_numeric($frame->body)) {
559             $id = intval($frame->body);
560             $info = "notice $id posted at {$frame->headers['created']} in queue $queue from $host";
561
562             $notice = Notice::staticGet('id', $id);
563             if (empty($notice)) {
564                 $this->_log(LOG_WARNING, "Skipping missing $info");
565                 $this->ack($idx, $frame);
566                 $this->commit($idx);
567                 $this->begin($idx);
568                 $this->stats('badnotice', $queue);
569                 return false;
570             }
571
572             $item = $notice;
573         } else {
574             // @fixme should we serialize, or json, or what here?
575             $info = "string posted at {$frame->headers['created']} in queue $queue from $host";
576             $item = $frame->body;
577         }
578
579         $handler = $this->getHandler($queue);
580         if (!$handler) {
581             $this->_log(LOG_ERR, "Missing handler class; skipping $info");
582             $this->ack($idx, $frame);
583             $this->commit($idx);
584             $this->begin($idx);
585             $this->stats('badhandler', $queue);
586             return false;
587         }
588
589         // If there's an exception when handling,
590         // log the error and let it get requeued.
591
592         try {
593             $ok = $handler->handle($item);
594         } catch (Exception $e) {
595             $this->_log(LOG_ERR, "Exception on queue $queue: " . $e->getMessage());
596             $ok = false;
597         }
598
599         if (!$ok) {
600             $this->_log(LOG_WARNING, "Failed handling $info");
601             // FIXME we probably shouldn't have to do
602             // this kind of queue management ourselves;
603             // if we don't ack, it should resend...
604             $this->ack($idx, $frame);
605             $this->enqueue($item, $queue);
606             $this->commit($idx);
607             $this->begin($idx);
608             $this->stats('requeued', $queue);
609             return false;
610         }
611
612         $this->_log(LOG_INFO, "Successfully handled $info");
613         $this->ack($idx, $frame);
614         $this->commit($idx);
615         $this->begin($idx);
616         $this->stats('handled', $queue);
617         return true;
618     }
619
620     /**
621      * Process a control signal broadcast.
622      *
623      * @param int $idx connection index
624      * @param array $frame Stomp frame
625      * @return bool true to continue; false to stop further processing.
626      */
627     protected function handleControlSignal($idx, $frame)
628     {
629         $message = trim($frame->body);
630         if (strpos($message, ':') !== false) {
631             list($event, $param) = explode(':', $message, 2);
632         } else {
633             $event = $message;
634             $param = '';
635         }
636
637         $shutdown = false;
638
639         if ($event == 'shutdown') {
640             $this->master->requestShutdown();
641             $shutdown = true;
642         } else if ($event == 'restart') {
643             $this->master->requestRestart();
644             $shutdown = true;
645         } else if ($event == 'update') {
646             $this->updateSiteConfig($param);
647         } else {
648             $this->_log(LOG_ERR, "Ignoring unrecognized control message: $message");
649         }
650
651         $this->ack($idx, $frame);
652         $this->commit($idx);
653         $this->begin($idx);
654         return $shutdown;
655     }
656
657     /**
658      * Set us up with queue subscriptions for a new site added at runtime,
659      * triggered by a broadcast to the 'statusnet-control' topic.
660      *
661      * @param array $frame Stomp frame
662      * @return bool true to continue; false to stop further processing.
663      */
664     protected function updateSiteConfig($nickname)
665     {
666         if (empty($this->sites)) {
667             if ($nickname == common_config('site', 'nickname')) {
668                 StatusNet::init(common_config('site', 'server'));
669                 $this->doUnsubscribe();
670                 $this->doSubscribe();
671             } else {
672                 $this->_log(LOG_INFO, "Ignoring update ping for other site $nickname");
673             }
674         } else {
675             $sn = Status_network::staticGet($nickname);
676             if ($sn) {
677                 $server = $sn->getServerName(); // @fixme do config-by-nick
678                 StatusNet::init($server);
679                 if (empty($this->sites[$server])) {
680                     $this->addSite($server);
681                 }
682                 $this->_log(LOG_INFO, "(Re)subscribing to queues for site $nickname / $server");
683                 $this->doUnsubscribe();
684                 $this->doSubscribe();
685                 $this->stats('siteupdate');
686             } else {
687                 $this->_log(LOG_ERR, "Ignoring ping for unrecognized new site $nickname");
688             }
689         }
690     }
691
692     /**
693      * Combines the queue_basename from configuration with the
694      * site server name and queue name to give eg:
695      *
696      * /queue/statusnet/identi.ca/sms
697      *
698      * @param string $queue
699      * @return string
700      */
701     protected function queueName($queue)
702     {
703         return common_config('queue', 'queue_basename') .
704             $this->currentSite() . '/' . $queue;
705     }
706
707     /**
708      * Returns the site and queue name from the server-side queue.
709      *
710      * @param string queue destination (eg '/queue/statusnet/identi.ca/sms')
711      * @return array of site and queue: ('identi.ca','sms') or false if unrecognized
712      */
713     protected function parseDestination($dest)
714     {
715         $prefix = common_config('queue', 'queue_basename');
716         if (substr($dest, 0, strlen($prefix)) == $prefix) {
717             $rest = substr($dest, strlen($prefix));
718             return explode("/", $rest, 2);
719         } else {
720             common_log(LOG_ERR, "Got a message from unrecognized stomp queue: $dest");
721             return array(false, false);
722         }
723     }
724
725     function _log($level, $msg)
726     {
727         common_log($level, 'StompQueueManager: '.$msg);
728     }
729
730     protected function begin($idx)
731     {
732         if ($this->useTransactions) {
733             if (!empty($this->transaction[$idx])) {
734                 throw new Exception("Tried to start transaction in the middle of a transaction");
735             }
736             $this->transactionCount[$idx]++;
737             $this->transaction[$idx] = $this->master->id . '-' . $this->transactionCount[$idx] . '-' . time();
738             $this->cons[$idx]->begin($this->transaction[$idx]);
739         }
740     }
741
742     protected function ack($idx, $frame)
743     {
744         if ($this->useTransactions) {
745             if (empty($this->transaction[$idx])) {
746                 throw new Exception("Tried to ack but not in a transaction");
747             }
748             $this->cons[$idx]->ack($frame, $this->transaction[$idx]);
749         } else {
750             $this->cons[$idx]->ack($frame);
751         }
752     }
753
754     protected function commit($idx)
755     {
756         if ($this->useTransactions) {
757             if (empty($this->transaction[$idx])) {
758                 throw new Exception("Tried to commit but not in a transaction");
759             }
760             $this->cons[$idx]->commit($this->transaction[$idx]);
761             $this->transaction[$idx] = null;
762         }
763     }
764
765     protected function rollback($idx)
766     {
767         if ($this->useTransactions) {
768             if (empty($this->transaction[$idx])) {
769                 throw new Exception("Tried to rollback but not in a transaction");
770             }
771             $this->cons[$idx]->commit($this->transaction[$idx]);
772             $this->transaction[$idx] = null;
773         }
774     }
775 }
776