]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/queuemanager.php
Merge branch 'master' of git@gitorious.org:statusnet/mainline
[quix0rs-gnu-social.git] / lib / queuemanager.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Abstract class for i/o 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  * @author    Brion Vibber <brion@status.net>
27  * @copyright 2009-2010 StatusNet, Inc.
28  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
29  * @link      http://status.net/
30  */
31
32 /**
33  * Completed child classes must implement the enqueue() method.
34  *
35  * For background processing, classes should implement either socket-based
36  * input (handleInput(), getSockets()) or idle-loop polling (idle()).
37  */
38 abstract class QueueManager extends IoManager
39 {
40     static $qm = null;
41
42     public $master = null;
43     public $handlers = array();
44     public $groups = array();
45
46     /**
47      * Factory function to pull the appropriate QueueManager object
48      * for this site's configuration. It can then be used to queue
49      * events for later processing or to spawn a processing loop.
50      *
51      * Plugins can add to the built-in types by hooking StartNewQueueManager.
52      *
53      * @return QueueManager
54      */
55     public static function get()
56     {
57         if (empty(self::$qm)) {
58
59             if (Event::handle('StartNewQueueManager', array(&self::$qm))) {
60
61                 $enabled = common_config('queue', 'enabled');
62                 $type = common_config('queue', 'subsystem');
63
64                 if (!$enabled) {
65                     // does everything immediately
66                     self::$qm = new UnQueueManager();
67                 } else {
68                     switch ($type) {
69                      case 'db':
70                         self::$qm = new DBQueueManager();
71                         break;
72                      case 'stomp':
73                         self::$qm = new StompQueueManager();
74                         break;
75                      default:
76                         throw new ServerException("No queue manager class for type '$type'");
77                     }
78                 }
79             }
80         }
81
82         return self::$qm;
83     }
84
85     /**
86      * @fixme wouldn't necessarily work with other class types.
87      * Better to change the interface...?
88      */
89     public static function multiSite()
90     {
91         if (common_config('queue', 'subsystem') == 'stomp') {
92             return IoManager::INSTANCE_PER_PROCESS;
93         } else {
94             return IoManager::SINGLE_ONLY;
95         }
96     }
97
98     function __construct()
99     {
100         $this->initialize();
101     }
102
103     /**
104      * Optional; ping any running queue handler daemons with a notification
105      * such as announcing a new site to handle or requesting clean shutdown.
106      * This avoids having to restart all the daemons manually to update configs
107      * and such.
108      *
109      * Called from scripts/queuectl.php controller utility.
110      *
111      * @param string $event event key
112      * @param string $param optional parameter to append to key
113      * @return boolean success
114      */
115     public function sendControlSignal($event, $param='')
116     {
117         throw new Exception(get_class($this) . " does not support control signals.");
118     }
119
120     /**
121      * Store an object (usually/always a Notice) into the given queue
122      * for later processing. No guarantee is made on when it will be
123      * processed; it could be immediately or at some unspecified point
124      * in the future.
125      *
126      * Must be implemented by any queue manager.
127      *
128      * @param Notice $object
129      * @param string $queue
130      */
131     abstract function enqueue($object, $queue);
132
133     /**
134      * Build a representation for an object for logging
135      * @param mixed
136      * @return string
137      */
138     function logrep($object) {
139         if (is_object($object)) {
140             $class = get_class($object);
141             if (isset($object->id)) {
142                 return "$class $object->id";
143             }
144             return $class;
145         }
146         if (is_string($object)) {
147             $len = strlen($object);
148             $fragment = mb_substr($object, 0, 32);
149             if (mb_strlen($object) > 32) {
150                 $fragment .= '...';
151             }
152             return "string '$fragment' ($len bytes)";
153         }
154         return strval($object);
155     }
156
157     /**
158      * Encode an object for queued storage.
159      * Next gen may use serialization.
160      *
161      * @param mixed $object
162      * @return string
163      */
164     protected function encode($object)
165     {
166         if ($object instanceof Notice) {
167             return $object->id;
168         } else if (is_string($object)) {
169             return $object;
170         } else {
171             throw new ServerException("Can't queue this type", 500);
172         }
173     }
174
175     /**
176      * Decode an object from queued storage.
177      * Accepts back-compat notice reference entries and strings for now.
178      *
179      * @param string
180      * @return mixed
181      */
182     protected function decode($frame)
183     {
184         if (is_numeric($frame)) {
185             return Notice::staticGet(intval($frame));
186         } else {
187             return $frame;
188         }
189     }
190
191     /**
192      * Instantiate the appropriate QueueHandler class for the given queue.
193      *
194      * @param string $queue
195      * @return mixed QueueHandler or null
196      */
197     function getHandler($queue)
198     {
199         if (isset($this->handlers[$queue])) {
200             $class = $this->handlers[$queue];
201             if (class_exists($class)) {
202                 return new $class();
203             } else {
204                 common_log(LOG_ERR, "Nonexistent handler class '$class' for queue '$queue'");
205             }
206         } else {
207             common_log(LOG_ERR, "Requested handler for unkown queue '$queue'");
208         }
209         return null;
210     }
211
212     /**
213      * Get a list of registered queue transport names to be used
214      * for this daemon.
215      *
216      * @return array of strings
217      */
218     function getQueues()
219     {
220         $group = $this->activeGroup();
221         return array_keys($this->groups[$group]);
222     }
223
224     /**
225      * Initialize the list of queue handlers
226      *
227      * @event StartInitializeQueueManager
228      * @event EndInitializeQueueManager
229      */
230     function initialize()
231     {
232         // @fixme we'll want to be able to listen to particular queues...
233         if (Event::handle('StartInitializeQueueManager', array($this))) {
234             $this->connect('plugin', 'PluginQueueHandler');
235             $this->connect('omb', 'OmbQueueHandler');
236             $this->connect('ping', 'PingQueueHandler');
237             $this->connect('distrib', 'DistribQueueHandler');
238             if (common_config('sms', 'enabled')) {
239                 $this->connect('sms', 'SmsQueueHandler');
240             }
241
242             // XMPP output handlers...
243             $this->connect('jabber', 'JabberQueueHandler');
244             $this->connect('public', 'PublicQueueHandler');
245             // @fixme this should get an actual queue
246             //$this->connect('confirm', 'XmppConfirmHandler');
247
248             // For compat with old plugins not registering their own handlers.
249             $this->connect('plugin', 'PluginQueueHandler');
250
251             $this->connect('xmppout', 'XmppOutQueueHandler', 'xmppdaemon');
252
253         }
254         Event::handle('EndInitializeQueueManager', array($this));
255     }
256
257     /**
258      * Register a queue transport name and handler class for your plugin.
259      * Only registered transports will be reliably picked up!
260      *
261      * @param string $transport
262      * @param string $class
263      * @param string $group
264      */
265     public function connect($transport, $class, $group='queuedaemon')
266     {
267         $this->handlers[$transport] = $class;
268         $this->groups[$group][$transport] = $class;
269     }
270
271     /**
272      * @return string queue group to use for this request
273      */
274     function activeGroup()
275     {
276         $group = 'queuedaemon';
277         if ($this->master) {
278             // hack hack
279             if ($this->master instanceof XmppMaster) {
280                 return 'xmppdaemon';
281             }
282         }
283         return $group;
284     }
285
286     /**
287      * Send a statistic ping to the queue monitoring system,
288      * optionally with a per-queue id.
289      *
290      * @param string $key
291      * @param string $queue
292      */
293     function stats($key, $queue=false)
294     {
295         $owners = array();
296         if ($queue) {
297             $owners[] = "queue:$queue";
298             $owners[] = "site:" . common_config('site', 'server');
299         }
300         if (isset($this->master)) {
301             $this->master->stats($key, $owners);
302         } else {
303             $monitor = new QueueMonitor();
304             $monitor->stats($key, $owners);
305         }
306     }
307 }