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;
59 $this->initManagers();
63 * Initialize IoManagers which are appropriate to this instance;
64 * pass class names or instances into $this->instantiate().
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.
69 * Switching site configurations is an acceptable side effect.
71 abstract function initManagers();
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.
78 * @param mixed $manager class name (to run $class::get()) or object
80 protected function instantiate($manager)
82 if (is_string($manager)) {
83 $manager = call_user_func(array($class, 'get'));
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.");
91 } else if ($caps == IoManager::INSTANCE_PER_PROCESS) {
95 if (!in_array($manager, $this->managers, true)) {
96 // Only need to save singletons once
97 $this->managers[] = $manager;
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.
110 $this->logState('init');
112 $this->checkMemory(false);
114 while (!$this->shutdown) {
115 $timeouts = array_values($this->pollTimeouts);
116 $timeouts[] = 60; // default max timeout
118 // Wait for something on one of our sockets
121 foreach ($this->managers as $manager) {
122 foreach ($manager->getSockets() as $socket) {
123 $sockets[] = $socket;
124 $managers[] = $manager;
126 $timeouts[] = intval($manager->timeout());
129 $timeout = min($timeouts);
134 $this->logState('listening');
135 //common_debug("Waiting up to $timeout seconds for socket data...");
136 $ready = stream_select($read, $write, $except, $timeout, 0);
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);
147 common_log(LOG_ERR, "Saw input on a socket we didn't listen to");
153 if ($timeout > 0 && empty($sockets)) {
154 // If we had no listeners, sleep until the pollers' next requested wakeup.
155 common_debug("Sleeping $timeout seconds until next poll cycle...");
156 $this->logState('sleep');
160 $this->logState('poll');
163 $this->logState('idle');
166 $this->checkMemory();
169 $this->logState('shutdown');
174 * Check runtime memory usage, possibly triggering a graceful shutdown
175 * and thread respawn if we've crossed the soft limit.
177 * @param boolean $respawn if false we'll shut down instead of respawning
179 protected function checkMemory($respawn=true)
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.");
187 $this->requestRestart();
189 $this->requestShutdown();
191 } else if (common_config('queue', 'debug_memory')) {
192 $fmt = number_format($usage);
193 common_debug("Memory usage $fmt");
199 * Return fully-parsed soft memory limit in bytes.
200 * @return intval 0 or -1 if not set
202 function softMemoryLimit()
204 $softLimit = trim(common_config('queue', 'softlimit'));
205 if (substr($softLimit, -1) == '%') {
206 $limit = $this->parseMemoryLimit(ini_get('memory_limit'));
208 return intval(substr($softLimit, 0, -1) * $limit / 100);
213 return $this->parseMemoryLimit($softLimit);
219 * Interpret PHP shorthand for memory_limit and friends.
220 * Why don't they just expose the actual numeric value? :P
224 public function parseMemoryLimit($mem)
226 // http://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
227 $mem = strtolower(trim($mem));
228 $size = array('k' => 1024,
230 'g' => 1024*1024*1024);
233 } else if (is_numeric($mem)) {
236 $mult = substr($mem, -1);
237 if (isset($size[$mult])) {
238 return substr($mem, 0, -1) * $size[$mult];
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;
260 foreach ($this->managers as $manager) {
262 // @fixme error check
267 * Called during the idle portion of the runloop to see which handlers
271 foreach ($this->managers as $index => $manager) {
272 $interval = $manager->pollInterval();
273 if ($interval <= 0) {
274 // Not a polling manager.
278 if (isset($this->pollTimeouts[$index])) {
279 $timeout = $this->pollTimeouts[$index];
280 if (time() - $this->lastPoll[$index] < $timeout) {
281 // Not time to poll yet.
287 $hit = $manager->poll();
289 $this->lastPoll[$index] = time();
291 // Do the next poll quickly, there may be more input!
292 $this->pollTimeouts[$index] = 0;
294 // Empty queue. Exponential backoff up to the maximum poll interval.
296 $timeout = min($timeout * 2, $interval);
300 $this->pollTimeouts[$index] = $timeout;
306 * Called after each handled item or empty polling cycle.
307 * This is a good time to e.g. service your XMPP connection.
311 foreach ($this->managers as $manager) {
317 * Send thread state update to the monitoring server, if configured.
319 * @param string $state ('init', 'queue', 'shutdown' etc)
320 * @param string $substate (optional, eg queue name 'omb' 'sms' etc)
322 protected function logState($state, $substate='')
324 $this->monitor->logState($this->id, $state, $substate);
329 * Thread ID will be implicit; other owners can be listed as well
330 * for per-queue and per-site records.
332 * @param string $key counter name
333 * @param array $owners list of owner keys like 'queue:xmpp' or 'site:stat01'
335 public function stats($key, $owners=array())
337 $owners[] = "thread:" . $this->id;
338 $this->monitor->stats($key, $owners);
342 * For IoManagers to request a graceful shutdown at end of event loop.
344 public function requestShutdown()
346 $this->shutdown = true;
347 $this->respawn = false;
351 * For IoManagers to request a graceful restart at end of event loop.
353 public function requestRestart()
355 $this->shutdown = true;
356 $this->respawn = true;