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