]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/queuemanager.php
Merge branch 'testing' into moveaccount
[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     protected $master = null;
43     protected $handlers = array();
44     protected $groups = array();
45     protected $activeGroups = array();
46
47     /**
48      * Factory function to pull the appropriate QueueManager object
49      * for this site's configuration. It can then be used to queue
50      * events for later processing or to spawn a processing loop.
51      *
52      * Plugins can add to the built-in types by hooking StartNewQueueManager.
53      *
54      * @return QueueManager
55      */
56     public static function get()
57     {
58         if (empty(self::$qm)) {
59
60             if (Event::handle('StartNewQueueManager', array(&self::$qm))) {
61
62                 $enabled = common_config('queue', 'enabled');
63                 $type = common_config('queue', 'subsystem');
64
65                 if (!$enabled) {
66                     // does everything immediately
67                     self::$qm = new UnQueueManager();
68                 } else {
69                     switch ($type) {
70                      case 'db':
71                         self::$qm = new DBQueueManager();
72                         break;
73                      case 'stomp':
74                         self::$qm = new StompQueueManager();
75                         break;
76                      default:
77                         throw new ServerException("No queue manager class for type '$type'");
78                     }
79                 }
80             }
81         }
82
83         return self::$qm;
84     }
85
86     /**
87      * @fixme wouldn't necessarily work with other class types.
88      * Better to change the interface...?
89      */
90     public static function multiSite()
91     {
92         if (common_config('queue', 'subsystem') == 'stomp') {
93             return IoManager::INSTANCE_PER_PROCESS;
94         } else {
95             return IoManager::SINGLE_ONLY;
96         }
97     }
98
99     function __construct()
100     {
101         $this->initialize();
102     }
103
104     /**
105      * Optional; ping any running queue handler daemons with a notification
106      * such as announcing a new site to handle or requesting clean shutdown.
107      * This avoids having to restart all the daemons manually to update configs
108      * and such.
109      *
110      * Called from scripts/queuectl.php controller utility.
111      *
112      * @param string $event event key
113      * @param string $param optional parameter to append to key
114      * @return boolean success
115      */
116     public function sendControlSignal($event, $param='')
117     {
118         throw new Exception(get_class($this) . " does not support control signals.");
119     }
120
121     /**
122      * Store an object (usually/always a Notice) into the given queue
123      * for later processing. No guarantee is made on when it will be
124      * processed; it could be immediately or at some unspecified point
125      * in the future.
126      *
127      * Must be implemented by any queue manager.
128      *
129      * @param Notice $object
130      * @param string $queue
131      */
132     abstract function enqueue($object, $queue);
133
134     /**
135      * Build a representation for an object for logging
136      * @param mixed
137      * @return string
138      */
139     function logrep($object) {
140         if (is_object($object)) {
141             $class = get_class($object);
142             if (isset($object->id)) {
143                 return "$class $object->id";
144             }
145             return $class;
146         }
147         if (is_string($object)) {
148             $len = strlen($object);
149             $fragment = mb_substr($object, 0, 32);
150             if (mb_strlen($object) > 32) {
151                 $fragment .= '...';
152             }
153             return "string '$fragment' ($len bytes)";
154         }
155         return strval($object);
156     }
157
158     /**
159      * Encode an object or variable for queued storage.
160      * Notice objects are currently stored as an id reference;
161      * other items are serialized.
162      *
163      * @param mixed $item
164      * @return string
165      */
166     protected function encode($item)
167     {
168         if ($item instanceof Notice) {
169             // Backwards compat
170             return $item->id;
171         } else {
172             return serialize($item);
173         }
174     }
175
176     /**
177      * Decode an object from queued storage.
178      * Accepts notice reference entries and serialized items.
179      *
180      * @param string
181      * @return mixed
182      */
183     protected function decode($frame)
184     {
185         if (is_numeric($frame)) {
186             // Back-compat for notices...
187             return Notice::staticGet(intval($frame));
188         } elseif (substr($frame, 0, 1) == '<') {
189             // Back-compat for XML source
190             return $frame;
191         } else {
192             // Deserialize!
193             #$old = error_reporting();
194             #error_reporting($old & ~E_NOTICE);
195             $out = unserialize($frame);
196             #error_reporting($old);
197
198             if ($out === false && $frame !== 'b:0;') {
199                 common_log(LOG_ERR, "Couldn't unserialize queued frame: $frame");
200                 return false;
201             }
202             return $out;
203         }
204     }
205
206     /**
207      * Instantiate the appropriate QueueHandler class for the given queue.
208      *
209      * @param string $queue
210      * @return mixed QueueHandler or null
211      */
212     function getHandler($queue)
213     {
214         if (isset($this->handlers[$queue])) {
215             $class = $this->handlers[$queue];
216             if(is_object($class)) {
217                 return $class;
218             } else if (class_exists($class)) {
219                 return new $class();
220             } else {
221                 $this->_log(LOG_ERR, "Nonexistent handler class '$class' for queue '$queue'");
222             }
223         } else {
224             $this->_log(LOG_ERR, "Requested handler for unkown queue '$queue'");
225         }
226         return null;
227     }
228
229     /**
230      * Get a list of registered queue transport names to be used
231      * for listening in this daemon.
232      *
233      * @return array of strings
234      */
235     function activeQueues()
236     {
237         $queues = array();
238         foreach ($this->activeGroups as $group) {
239             if (isset($this->groups[$group])) {
240                 $queues = array_merge($queues, $this->groups[$group]);
241             }
242         }
243
244         return array_keys($queues);
245     }
246
247     /**
248      * Initialize the list of queue handlers for the current site.
249      *
250      * @event StartInitializeQueueManager
251      * @event EndInitializeQueueManager
252      */
253     function initialize()
254     {
255         $this->handlers = array();
256         $this->groups = array();
257         $this->groupsByTransport = array();
258
259         if (Event::handle('StartInitializeQueueManager', array($this))) {
260             $this->connect('distrib', 'DistribQueueHandler');
261             $this->connect('omb', 'OmbQueueHandler');
262             $this->connect('ping', 'PingQueueHandler');
263             if (common_config('sms', 'enabled')) {
264                 $this->connect('sms', 'SmsQueueHandler');
265             }
266
267             // Background user management tasks...
268             $this->connect('deluser', 'DelUserQueueHandler');
269             $this->connect('feedimp', 'FeedImporter');
270             $this->connect('actimp', 'ActivityImporter');
271             $this->connect('acctmove', 'AccountMover');
272             $this->connect('actmove', 'ActivityMover');
273
274             // Broadcasting profile updates to OMB remote subscribers
275             $this->connect('profile', 'ProfileQueueHandler');
276
277             // XMPP output handlers...
278             if (common_config('xmpp', 'enabled')) {
279                 // Delivery prep, read by queuedaemon.php:
280                 $this->connect('jabber', 'JabberQueueHandler');
281                 $this->connect('public', 'PublicQueueHandler');
282
283                 // Raw output, read by xmppdaemon.php:
284                 $this->connect('xmppout', 'XmppOutQueueHandler', 'xmpp');
285             }
286
287             // For compat with old plugins not registering their own handlers.
288             $this->connect('plugin', 'PluginQueueHandler');
289         }
290         Event::handle('EndInitializeQueueManager', array($this));
291     }
292
293     /**
294      * Register a queue transport name and handler class for your plugin.
295      * Only registered transports will be reliably picked up!
296      *
297      * @param string $transport
298      * @param string $class class name or object instance
299      * @param string $group
300      */
301     public function connect($transport, $class, $group='main')
302     {
303         $this->handlers[$transport] = $class;
304         $this->groups[$group][$transport] = $class;
305         $this->groupsByTransport[$transport] = $group;
306     }
307
308     /**
309      * Set the active group which will be used for listening.
310      * @param string $group
311      */
312     function setActiveGroup($group)
313     {
314         $this->activeGroups = array($group);
315     }
316
317     /**
318      * Set the active group(s) which will be used for listening.
319      * @param array $groups
320      */
321     function setActiveGroups($groups)
322     {
323         $this->activeGroups = $groups;
324     }
325
326     /**
327      * @return string queue group for this queue
328      */
329     function queueGroup($queue)
330     {
331         if (isset($this->groupsByTransport[$queue])) {
332             return $this->groupsByTransport[$queue];
333         } else {
334             throw new Exception("Requested group for unregistered transport $queue");
335         }
336     }
337
338     /**
339      * Send a statistic ping to the queue monitoring system,
340      * optionally with a per-queue id.
341      *
342      * @param string $key
343      * @param string $queue
344      */
345     function stats($key, $queue=false)
346     {
347         $owners = array();
348         if ($queue) {
349             $owners[] = "queue:$queue";
350             $owners[] = "site:" . common_config('site', 'server');
351         }
352         if (isset($this->master)) {
353             $this->master->stats($key, $owners);
354         } else {
355             $monitor = new QueueMonitor();
356             $monitor->stats($key, $owners);
357         }
358     }
359
360     protected function _log($level, $msg)
361     {
362         $class = get_class($this);
363         if ($this->activeGroups) {
364             $groups = ' (' . implode(',', $this->activeGroups) . ')';
365         } else {
366             $groups = '';
367         }
368         common_log($level, "$class$groups: $msg");
369     }
370 }