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();
41 public $shutdown = false; // Did we do a graceful shutdown?
42 public $respawn = true; // Should we respawn after shutdown?
45 * @param string $id process ID to use in logging/monitoring
47 public function __construct($id)
50 $this->monitor = new QueueMonitor();
53 public function init($multiSite=null)
55 if ($multiSite !== null) {
56 $this->multiSite = $multiSite;
58 if ($this->multiSite) {
59 $this->sites = $this->findAllSites();
61 $this->sites = array(common_config('site', 'server'));
64 if (empty($this->sites)) {
65 throw new Exception("Empty status_network table, cannot init");
68 foreach ($this->sites as $site) {
69 if ($site != common_config('site', 'server')) {
70 StatusNet::init($site);
72 $this->initManagers();
77 * Initialize IoManagers for the currently configured site
78 * which are appropriate to this instance.
80 * Pass class names into $this->instantiate()
82 abstract function initManagers();
85 * Pull all local sites from status_network table.
86 * @return array of hostnames
88 protected function findAllSites()
91 $sn = new Status_network();
93 while ($sn->fetch()) {
94 $hosts[] = $sn->getServerName();
100 * Instantiate an i/o manager class for the current site.
101 * If a multi-site capable handler is already present,
102 * we don't need to build a new one.
104 * @param string $class
106 protected function instantiate($class)
108 if (is_string($class) && isset($this->singletons[$class])) {
109 // Already instantiated a multi-site-capable handler.
110 // Just let it know it should listen to this site too!
111 $this->singletons[$class]->addSite(common_config('site', 'server'));
115 $manager = $this->getManager($class);
117 if ($this->multiSite) {
118 $caps = $manager->multiSite();
119 if ($caps == IoManager::SINGLE_ONLY) {
120 throw new Exception("$class can't run with --all; aborting.");
122 if ($caps == IoManager::INSTANCE_PER_PROCESS) {
123 // Save this guy for later!
124 // We'll only need the one to cover multiple sites.
125 $this->singletons[$class] = $manager;
126 $manager->addSite(common_config('site', 'server'));
130 $this->managers[] = $manager;
133 protected function getManager($class)
135 if(is_object($class)){
138 return call_user_func(array($class, 'get'));
145 * Initialize all io managers, then sit around waiting for input.
146 * Between events or timeouts, pass control back to idle() method
147 * to allow for any additional background processing.
151 $this->logState('init');
154 while (!$this->shutdown) {
155 $timeouts = array_values($this->pollTimeouts);
156 $timeouts[] = 60; // default max timeout
158 // Wait for something on one of our sockets
161 foreach ($this->managers as $manager) {
162 foreach ($manager->getSockets() as $socket) {
163 $sockets[] = $socket;
164 $managers[] = $manager;
166 $timeouts[] = intval($manager->timeout());
169 $timeout = min($timeouts);
174 $this->logState('listening');
175 common_log(LOG_DEBUG, "Waiting up to $timeout seconds for socket data...");
176 $ready = stream_select($read, $write, $except, $timeout, 0);
178 if ($ready === false) {
179 common_log(LOG_ERR, "Error selecting on sockets");
180 } else if ($ready > 0) {
181 foreach ($read as $socket) {
182 $index = array_search($socket, $sockets, true);
183 if ($index !== false) {
184 $this->logState('queue');
185 $managers[$index]->handleInput($socket);
187 common_log(LOG_ERR, "Saw input on a socket we didn't listen to");
193 if ($timeout > 0 && empty($sockets)) {
194 // If we had no listeners, sleep until the pollers' next requested wakeup.
195 common_log(LOG_DEBUG, "Sleeping $timeout seconds until next poll cycle...");
196 $this->logState('sleep');
200 $this->logState('poll');
203 $this->logState('idle');
206 $this->checkMemory();
209 $this->logState('shutdown');
214 * Check runtime memory usage, possibly triggering a graceful shutdown
215 * and thread respawn if we've crossed the soft limit.
217 protected function checkMemory()
219 $memoryLimit = $this->softMemoryLimit();
220 if ($memoryLimit > 0) {
221 $usage = memory_get_usage();
222 if ($usage > $memoryLimit) {
223 common_log(LOG_INFO, "Queue thread hit soft memory limit ($usage > $memoryLimit); gracefully restarting.");
224 $this->requestRestart();
225 } else if (common_config('queue', 'debug_memory')) {
226 common_log(LOG_DEBUG, "Memory usage $usage");
232 * Return fully-parsed soft memory limit in bytes.
233 * @return intval 0 or -1 if not set
235 function softMemoryLimit()
237 $softLimit = trim(common_config('queue', 'softlimit'));
238 if (substr($softLimit, -1) == '%') {
239 $limit = $this->parseMemoryLimit(ini_get('memory_limit'));
241 return intval(substr($softLimit, 0, -1) * $limit / 100);
246 return $this->parseMemoryLimit($softLimit);
252 * Interpret PHP shorthand for memory_limit and friends.
253 * Why don't they just expose the actual numeric value? :P
257 public function parseMemoryLimit($mem)
259 // http://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
260 $mem = strtolower(trim($mem));
261 $size = array('k' => 1024,
263 'g' => 1024*1024*1024);
266 } else if (is_numeric($mem)) {
269 $mult = substr($mem, -1);
270 if (isset($size[$mult])) {
271 return substr($mem, 0, -1) * $size[$mult];
280 foreach ($this->managers as $index => $manager) {
281 $manager->start($this);
282 // @fixme error check
283 if ($manager->pollInterval()) {
284 // We'll want to check for input on the first pass
285 $this->pollTimeouts[$index] = 0;
286 $this->lastPoll[$index] = 0;
293 foreach ($this->managers as $manager) {
295 // @fixme error check
300 * Called during the idle portion of the runloop to see which handlers
304 foreach ($this->managers as $index => $manager) {
305 $interval = $manager->pollInterval();
306 if ($interval <= 0) {
307 // Not a polling manager.
311 if (isset($this->pollTimeouts[$index])) {
312 $timeout = $this->pollTimeouts[$index];
313 if (time() - $this->lastPoll[$index] < $timeout) {
314 // Not time to poll yet.
320 $hit = $manager->poll();
322 $this->lastPoll[$index] = time();
324 // Do the next poll quickly, there may be more input!
325 $this->pollTimeouts[$index] = 0;
327 // Empty queue. Exponential backoff up to the maximum poll interval.
329 $timeout = min($timeout * 2, $interval);
333 $this->pollTimeouts[$index] = $timeout;
339 * Called after each handled item or empty polling cycle.
340 * This is a good time to e.g. service your XMPP connection.
344 foreach ($this->managers as $manager) {
350 * Send thread state update to the monitoring server, if configured.
352 * @param string $state ('init', 'queue', 'shutdown' etc)
353 * @param string $substate (optional, eg queue name 'omb' 'sms' etc)
355 protected function logState($state, $substate='')
357 $this->monitor->logState($this->id, $state, $substate);
362 * Thread ID will be implicit; other owners can be listed as well
363 * for per-queue and per-site records.
365 * @param string $key counter name
366 * @param array $owners list of owner keys like 'queue:xmpp' or 'site:stat01'
368 public function stats($key, $owners=array())
370 $owners[] = "thread:" . $this->id;
371 $this->monitor->stats($key, $owners);
375 * For IoManagers to request a graceful shutdown at end of event loop.
377 public function requestShutdown()
379 $this->shutdown = true;
380 $this->respawn = false;
384 * For IoManagers to request a graceful restart at end of event loop.
386 public function requestRestart()
388 $this->shutdown = true;
389 $this->respawn = true;