]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/iomaster.php
XSS vulnerability when remote-subscribing
[quix0rs-gnu-social.git] / lib / iomaster.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * I/O manager to wrap around socket-reading and polling queue & connection 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    Brion Vibber <brion@status.net>
25  * @copyright 2009 StatusNet, Inc.
26  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
27  * @link      http://status.net/
28  */
29
30 abstract class IoMaster
31 {
32     public $id;
33
34     protected $multiSite = false;
35     protected $managers = array();
36     protected $singletons = array();
37
38     protected $pollTimeouts = array();
39     protected $lastPoll = array();
40
41     public $shutdown = false; // Did we do a graceful shutdown?
42     public $respawn = true; // Should we respawn after shutdown?
43
44     /**
45      * @param string $id process ID to use in logging/monitoring
46      */
47     public function __construct($id)
48     {
49         $this->id = $id;
50         $this->monitor = new QueueMonitor();
51     }
52
53     public function init($multiSite=null)
54     {
55         if ($multiSite !== null) {
56             $this->multiSite = $multiSite;
57         }
58
59         $this->initManagers();
60     }
61
62     /**
63      * Initialize IoManagers which are appropriate to this instance;
64      * pass class names or instances into $this->instantiate().
65      *
66      * If setup and configuration may vary between sites in multi-site
67      * mode, it's the subclass's responsibility to set them up here.
68      *
69      * Switching site configurations is an acceptable side effect.
70      */
71     abstract function initManagers();
72
73     /**
74      * Instantiate an i/o manager class for the current site.
75      * If a multi-site capable handler is already present,
76      * we don't need to build a new one.
77      *
78      * @param mixed $manager class name (to run $class::get()) or object
79      */
80     protected function instantiate($manager)
81     {
82         if (is_string($manager)) {
83             $manager = call_user_func(array($class, 'get'));
84         }
85
86         $caps = $manager->multiSite();
87         if ($caps == IoManager::SINGLE_ONLY) {
88             if ($this->multiSite) {
89                 throw new Exception("$class can't run with --all; aborting.");
90             }
91         } else if ($caps == IoManager::INSTANCE_PER_PROCESS) {
92             $manager->addSite();
93         }
94
95         if (!in_array($manager, $this->managers, true)) {
96             // Only need to save singletons once
97             $this->managers[] = $manager;
98         }
99     }
100
101     /**
102      * Basic run loop...
103      *
104      * Initialize all io managers, then sit around waiting for input.
105      * Between events or timeouts, pass control back to idle() method
106      * to allow for any additional background processing.
107      */
108     function service()
109     {
110         $this->logState('init');
111         $this->start();
112         $this->checkMemory(false);
113
114         while (!$this->shutdown) {
115             $timeouts = array_values($this->pollTimeouts);
116             $timeouts[] = 60; // default max timeout
117
118             // Wait for something on one of our sockets
119             $sockets = array();
120             $managers = array();
121             foreach ($this->managers as $manager) {
122                 foreach ($manager->getSockets() as $socket) {
123                     $sockets[] = $socket;
124                     $managers[] = $manager;
125                 }
126                 $timeouts[] = intval($manager->timeout());
127             }
128
129             $timeout = min($timeouts);
130             if ($sockets) {
131                 $read = $sockets;
132                 $write = array();
133                 $except = array();
134                 $this->logState('listening');
135                 //common_debug("Waiting up to $timeout seconds for socket data...");
136                 $ready = stream_select($read, $write, $except, $timeout, 0);
137
138                 if ($ready === false) {
139                     common_log(LOG_ERR, "Error selecting on sockets");
140                 } else if ($ready > 0) {
141                     foreach ($read as $socket) {
142                         $index = array_search($socket, $sockets, true);
143                         if ($index !== false) {
144                             $this->logState('queue');
145                             $managers[$index]->handleInput($socket);
146                         } else {
147                             common_log(LOG_ERR, "Saw input on a socket we didn't listen to");
148                         }
149                     }
150                 }
151             }
152
153             if ($timeout > 0 && empty($sockets)) {
154                 // If we had no listeners, sleep until the pollers' next requested wakeup.
155                 common_log(LOG_DEBUG, "Sleeping $timeout seconds until next poll cycle...");
156                 $this->logState('sleep');
157                 sleep($timeout);
158             }
159
160             $this->logState('poll');
161             $this->poll();
162
163             $this->logState('idle');
164             $this->idle();
165
166             $this->checkMemory();
167         }
168
169         $this->logState('shutdown');
170         $this->finish();
171     }
172
173     /**
174      * Check runtime memory usage, possibly triggering a graceful shutdown
175      * and thread respawn if we've crossed the soft limit.
176      *
177      * @param boolean $respawn if false we'll shut down instead of respawning
178      */
179     protected function checkMemory($respawn=true)
180     {
181         $memoryLimit = $this->softMemoryLimit();
182         if ($memoryLimit > 0) {
183             $usage = memory_get_usage();
184             if ($usage > $memoryLimit) {
185                 common_log(LOG_INFO, "Queue thread hit soft memory limit ($usage > $memoryLimit); gracefully restarting.");
186                 if ($respawn) {
187                     $this->requestRestart();
188                 } else {
189                     $this->requestShutdown();
190                 }
191             } else if (common_config('queue', 'debug_memory')) {
192                 $fmt = number_format($usage);
193                 common_log(LOG_DEBUG, "Memory usage $fmt");
194             }
195         }
196     }
197
198     /**
199      * Return fully-parsed soft memory limit in bytes.
200      * @return intval 0 or -1 if not set
201      */
202     function softMemoryLimit()
203     {
204         $softLimit = trim(common_config('queue', 'softlimit'));
205         if (substr($softLimit, -1) == '%') {
206             $limit = $this->parseMemoryLimit(ini_get('memory_limit'));
207             if ($limit > 0) {
208                 return intval(substr($softLimit, 0, -1) * $limit / 100);
209             } else {
210                 return -1;
211             }
212         } else {
213             return $this->parseMemoryLimit($softLimit);
214         }
215         return $softLimit;
216     }
217
218     /**
219      * Interpret PHP shorthand for memory_limit and friends.
220      * Why don't they just expose the actual numeric value? :P
221      * @param string $mem
222      * @return int
223      */
224     public function parseMemoryLimit($mem)
225     {
226         // http://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
227         $mem = strtolower(trim($mem));
228         $size = array('k' => 1024,
229                       'm' => 1024*1024,
230                       'g' => 1024*1024*1024);
231         if (empty($mem)) {
232             return 0;
233         } else if (is_numeric($mem)) {
234             return intval($mem);
235         } else {
236             $mult = substr($mem, -1);
237             if (isset($size[$mult])) {
238                 return substr($mem, 0, -1) * $size[$mult];
239             } else {
240                 return intval($mem);
241             }
242         }
243     }
244
245     function start()
246     {
247         foreach ($this->managers as $index => $manager) {
248             $manager->start($this);
249             // @fixme error check
250             if ($manager->pollInterval()) {
251                 // We'll want to check for input on the first pass
252                 $this->pollTimeouts[$index] = 0;
253                 $this->lastPoll[$index] = 0;
254             }
255         }
256     }
257
258     function finish()
259     {
260         foreach ($this->managers as $manager) {
261             $manager->finish();
262             // @fixme error check
263         }
264     }
265
266     /**
267      * Called during the idle portion of the runloop to see which handlers
268      */
269     function poll()
270     {
271         foreach ($this->managers as $index => $manager) {
272             $interval = $manager->pollInterval();
273             if ($interval <= 0) {
274                 // Not a polling manager.
275                 continue;
276             }
277
278             if (isset($this->pollTimeouts[$index])) {
279                 $timeout = $this->pollTimeouts[$index];
280                 if (time() - $this->lastPoll[$index] < $timeout) {
281                     // Not time to poll yet.
282                     continue;
283                 }
284             } else {
285                 $timeout = 0;
286             }
287             $hit = $manager->poll();
288
289             $this->lastPoll[$index] = time();
290             if ($hit) {
291                 // Do the next poll quickly, there may be more input!
292                 $this->pollTimeouts[$index] = 0;
293             } else {
294                 // Empty queue. Exponential backoff up to the maximum poll interval.
295                 if ($timeout > 0) {
296                     $timeout = min($timeout * 2, $interval);
297                 } else {
298                     $timeout = 1;
299                 }
300                 $this->pollTimeouts[$index] = $timeout;
301             }
302         }
303     }
304
305     /**
306      * Called after each handled item or empty polling cycle.
307      * This is a good time to e.g. service your XMPP connection.
308      */
309     function idle()
310     {
311         foreach ($this->managers as $manager) {
312             $manager->idle();
313         }
314     }
315
316     /**
317      * Send thread state update to the monitoring server, if configured.
318      *
319      * @param string $state ('init', 'queue', 'shutdown' etc)
320      * @param string $substate (optional, eg queue name 'omb' 'sms' etc)
321      */
322     protected function logState($state, $substate='')
323     {
324         $this->monitor->logState($this->id, $state, $substate);
325     }
326
327     /**
328      * Send thread stats.
329      * Thread ID will be implicit; other owners can be listed as well
330      * for per-queue and per-site records.
331      *
332      * @param string $key counter name
333      * @param array $owners list of owner keys like 'queue:xmpp' or 'site:stat01'
334      */
335     public function stats($key, $owners=array())
336     {
337         $owners[] = "thread:" . $this->id;
338         $this->monitor->stats($key, $owners);
339     }
340
341     /**
342      * For IoManagers to request a graceful shutdown at end of event loop.
343      */
344     public function requestShutdown()
345     {
346         $this->shutdown = true;
347         $this->respawn = false;
348     }
349
350     /**
351      * For IoManagers to request a graceful restart at end of event loop.
352      */
353     public function requestRestart()
354     {
355         $this->shutdown = true;
356         $this->respawn = true;
357     }
358
359 }
360