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