3 * StatusNet, the distributed open-source microblogging tool
5 * I/O manager to wrap around socket-reading and polling queue & connection managers.
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.
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.
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/>.
22 * @category QueueManager
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/
30 abstract class IoMaster
34 protected $multiSite = false;
35 protected $managers = array();
36 protected $singletons = array();
38 protected $pollTimeouts = array();
39 protected $lastPoll = array();
42 * @param string $id process ID to use in logging/monitoring
44 public function __construct($id)
47 $this->monitor = new QueueMonitor();
50 public function init($multiSite=null)
52 if ($multiSite !== null) {
53 $this->multiSite = $multiSite;
55 if ($this->multiSite) {
56 $this->sites = $this->findAllSites();
58 $this->sites = array(common_config('site', 'server'));
61 if (empty($this->sites)) {
62 throw new Exception("Empty status_network table, cannot init");
65 foreach ($this->sites as $site) {
66 if ($site != common_config('site', 'server')) {
67 StatusNet::init($site);
69 $this->initManagers();
74 * Initialize IoManagers for the currently configured site
75 * which are appropriate to this instance.
77 * Pass class names into $this->instantiate()
79 abstract function initManagers();
82 * Pull all local sites from status_network table.
83 * @return array of hostnames
85 protected function findAllSites()
88 $sn = new Status_network();
90 while ($sn->fetch()) {
91 $hosts[] = $sn->getServerName();
97 * Instantiate an i/o manager class for the current site.
98 * If a multi-site capable handler is already present,
99 * we don't need to build a new one.
101 * @param string $class
103 protected function instantiate($class)
105 if (is_string($class) && isset($this->singletons[$class])) {
106 // Already instantiated a multi-site-capable handler.
107 // Just let it know it should listen to this site too!
108 $this->singletons[$class]->addSite(common_config('site', 'server'));
112 $manager = $this->getManager($class);
114 if ($this->multiSite) {
115 $caps = $manager->multiSite();
116 if ($caps == IoManager::SINGLE_ONLY) {
117 throw new Exception("$class can't run with --all; aborting.");
119 if ($caps == IoManager::INSTANCE_PER_PROCESS) {
120 // Save this guy for later!
121 // We'll only need the one to cover multiple sites.
122 $this->singletons[$class] = $manager;
123 $manager->addSite(common_config('site', 'server'));
127 $this->managers[] = $manager;
130 protected function getManager($class)
132 if(is_object($class)){
135 return call_user_func(array($class, 'get'));
142 * Initialize all io managers, then sit around waiting for input.
143 * Between events or timeouts, pass control back to idle() method
144 * to allow for any additional background processing.
148 $this->logState('init');
152 $timeouts = array_values($this->pollTimeouts);
153 $timeouts[] = 60; // default max timeout
155 // Wait for something on one of our sockets
158 foreach ($this->managers as $manager) {
159 foreach ($manager->getSockets() as $socket) {
160 $sockets[] = $socket;
161 $managers[] = $manager;
163 $timeouts[] = intval($manager->timeout());
166 $timeout = min($timeouts);
171 $this->logState('listening');
172 common_log(LOG_DEBUG, "Waiting up to $timeout seconds for socket data...");
173 $ready = stream_select($read, $write, $except, $timeout, 0);
175 if ($ready === false) {
176 common_log(LOG_ERR, "Error selecting on sockets");
177 } else if ($ready > 0) {
178 foreach ($read as $socket) {
179 $index = array_search($socket, $sockets, true);
180 if ($index !== false) {
181 $this->logState('queue');
182 $managers[$index]->handleInput($socket);
184 common_log(LOG_ERR, "Saw input on a socket we didn't listen to");
190 if ($timeout > 0 && empty($sockets)) {
191 // If we had no listeners, sleep until the pollers' next requested wakeup.
192 common_log(LOG_DEBUG, "Sleeping $timeout seconds until next poll cycle...");
193 $this->logState('sleep');
197 $this->logState('poll');
200 $this->logState('idle');
203 $memoryLimit = $this->softMemoryLimit();
204 if ($memoryLimit > 0) {
205 $usage = memory_get_usage();
206 if ($usage > $memoryLimit) {
207 common_log(LOG_INFO, "Queue thread hit soft memory limit ($usage > $memoryLimit); gracefully restarting.");
209 } else if (common_config('queue', 'debug_memory')) {
210 common_log(LOG_DEBUG, "Memory usage $usage");
215 $this->logState('shutdown');
220 * Return fully-parsed soft memory limit in bytes.
221 * @return intval 0 or -1 if not set
223 function softMemoryLimit()
225 $softLimit = trim(common_config('queue', 'softlimit'));
226 if (substr($softLimit, -1) == '%') {
227 $limit = $this->parseMemoryLimit(ini_get('memory_limit'));
229 return intval(substr($softLimit, 0, -1) * $limit / 100);
234 return $this->parseMemoryLimit($softLimit);
240 * Interpret PHP shorthand for memory_limit and friends.
241 * Why don't they just expose the actual numeric value? :P
245 public function parseMemoryLimit($mem)
247 // http://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
248 $mem = strtolower(trim($mem));
249 $size = array('k' => 1024,
251 'g' => 1024*1024*1024);
254 } else if (is_numeric($mem)) {
257 $mult = substr($mem, -1);
258 if (isset($size[$mult])) {
259 return substr($mem, 0, -1) * $size[$mult];
268 foreach ($this->managers as $index => $manager) {
269 $manager->start($this);
270 // @fixme error check
271 if ($manager->pollInterval()) {
272 // We'll want to check for input on the first pass
273 $this->pollTimeouts[$index] = 0;
274 $this->lastPoll[$index] = 0;
281 foreach ($this->managers as $manager) {
283 // @fixme error check
288 * Called during the idle portion of the runloop to see which handlers
292 foreach ($this->managers as $index => $manager) {
293 $interval = $manager->pollInterval();
294 if ($interval <= 0) {
295 // Not a polling manager.
299 if (isset($this->pollTimeouts[$index])) {
300 $timeout = $this->pollTimeouts[$index];
301 if (time() - $this->lastPoll[$index] < $timeout) {
302 // Not time to poll yet.
308 $hit = $manager->poll();
310 $this->lastPoll[$index] = time();
312 // Do the next poll quickly, there may be more input!
313 $this->pollTimeouts[$index] = 0;
315 // Empty queue. Exponential backoff up to the maximum poll interval.
317 $timeout = min($timeout * 2, $interval);
321 $this->pollTimeouts[$index] = $timeout;
327 * Called after each handled item or empty polling cycle.
328 * This is a good time to e.g. service your XMPP connection.
332 foreach ($this->managers as $manager) {
338 * Send thread state update to the monitoring server, if configured.
340 * @param string $state ('init', 'queue', 'shutdown' etc)
341 * @param string $substate (optional, eg queue name 'omb' 'sms' etc)
343 protected function logState($state, $substate='')
345 $this->monitor->logState($this->id, $state, $substate);
350 * Thread ID will be implicit; other owners can be listed as well
351 * for per-queue and per-site records.
353 * @param string $key counter name
354 * @param array $owners list of owner keys like 'queue:xmpp' or 'site:stat01'
356 public function stats($key, $owners=array())
358 $owners[] = "thread:" . $this->id;
359 $this->monitor->stats($key, $owners);