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