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 (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 return call_user_func(array($class, 'get'));
141 * Initialize all io managers, then sit around waiting for input.
142 * Between events or timeouts, pass control back to idle() method
143 * to allow for any additional background processing.
147 $this->logState('init');
150 while (!$this->shutdown) {
151 $timeouts = array_values($this->pollTimeouts);
152 $timeouts[] = 60; // default max timeout
154 // Wait for something on one of our sockets
157 foreach ($this->managers as $manager) {
158 foreach ($manager->getSockets() as $socket) {
159 $sockets[] = $socket;
160 $managers[] = $manager;
162 $timeouts[] = intval($manager->timeout());
165 $timeout = min($timeouts);
170 $this->logState('listening');
171 common_log(LOG_DEBUG, "Waiting up to $timeout seconds for socket data...");
172 $ready = stream_select($read, $write, $except, $timeout, 0);
174 if ($ready === false) {
175 common_log(LOG_ERR, "Error selecting on sockets");
176 } else if ($ready > 0) {
177 foreach ($read as $socket) {
178 $index = array_search($socket, $sockets, true);
179 if ($index !== false) {
180 $this->logState('queue');
181 $managers[$index]->handleInput($socket);
183 common_log(LOG_ERR, "Saw input on a socket we didn't listen to");
189 if ($timeout > 0 && empty($sockets)) {
190 // If we had no listeners, sleep until the pollers' next requested wakeup.
191 common_log(LOG_DEBUG, "Sleeping $timeout seconds until next poll cycle...");
192 $this->logState('sleep');
196 $this->logState('poll');
199 $this->logState('idle');
202 $this->checkMemory();
205 $this->logState('shutdown');
210 * Check runtime memory usage, possibly triggering a graceful shutdown
211 * and thread respawn if we've crossed the soft limit.
213 protected function checkMemory()
215 $memoryLimit = $this->softMemoryLimit();
216 if ($memoryLimit > 0) {
217 $usage = memory_get_usage();
218 if ($usage > $memoryLimit) {
219 common_log(LOG_INFO, "Queue thread hit soft memory limit ($usage > $memoryLimit); gracefully restarting.");
220 $this->requestRestart();
221 } else if (common_config('queue', 'debug_memory')) {
222 common_log(LOG_DEBUG, "Memory usage $usage");
228 * Return fully-parsed soft memory limit in bytes.
229 * @return intval 0 or -1 if not set
231 function softMemoryLimit()
233 $softLimit = trim(common_config('queue', 'softlimit'));
234 if (substr($softLimit, -1) == '%') {
235 $limit = $this->parseMemoryLimit(ini_get('memory_limit'));
237 return intval(substr($softLimit, 0, -1) * $limit / 100);
242 return $this->parseMemoryLimit($softLimit);
248 * Interpret PHP shorthand for memory_limit and friends.
249 * Why don't they just expose the actual numeric value? :P
253 public function parseMemoryLimit($mem)
255 // http://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
256 $mem = strtolower(trim($mem));
257 $size = array('k' => 1024,
259 'g' => 1024*1024*1024);
262 } else if (is_numeric($mem)) {
265 $mult = substr($mem, -1);
266 if (isset($size[$mult])) {
267 return substr($mem, 0, -1) * $size[$mult];
276 foreach ($this->managers as $index => $manager) {
277 $manager->start($this);
278 // @fixme error check
279 if ($manager->pollInterval()) {
280 // We'll want to check for input on the first pass
281 $this->pollTimeouts[$index] = 0;
282 $this->lastPoll[$index] = 0;
289 foreach ($this->managers as $manager) {
291 // @fixme error check
296 * Called during the idle portion of the runloop to see which handlers
300 foreach ($this->managers as $index => $manager) {
301 $interval = $manager->pollInterval();
302 if ($interval <= 0) {
303 // Not a polling manager.
307 if (isset($this->pollTimeouts[$index])) {
308 $timeout = $this->pollTimeouts[$index];
309 if (time() - $this->lastPoll[$index] < $timeout) {
310 // Not time to poll yet.
316 $hit = $manager->poll();
318 $this->lastPoll[$index] = time();
320 // Do the next poll quickly, there may be more input!
321 $this->pollTimeouts[$index] = 0;
323 // Empty queue. Exponential backoff up to the maximum poll interval.
325 $timeout = min($timeout * 2, $interval);
329 $this->pollTimeouts[$index] = $timeout;
335 * Called after each handled item or empty polling cycle.
336 * This is a good time to e.g. service your XMPP connection.
340 foreach ($this->managers as $manager) {
346 * Send thread state update to the monitoring server, if configured.
348 * @param string $state ('init', 'queue', 'shutdown' etc)
349 * @param string $substate (optional, eg queue name 'omb' 'sms' etc)
351 protected function logState($state, $substate='')
353 $this->monitor->logState($this->id, $state, $substate);
358 * Thread ID will be implicit; other owners can be listed as well
359 * for per-queue and per-site records.
361 * @param string $key counter name
362 * @param array $owners list of owner keys like 'queue:jabber' or 'site:stat01'
364 public function stats($key, $owners=array())
366 $owners[] = "thread:" . $this->id;
367 $this->monitor->stats($key, $owners);
371 * For IoManagers to request a graceful shutdown at end of event loop.
373 public function requestShutdown()
375 $this->shutdown = true;
376 $this->respawn = false;
380 * For IoManagers to request a graceful restart at end of event loop.
382 public function requestRestart()
384 $this->shutdown = true;
385 $this->respawn = true;