2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Redis based session handler.
21 * @copyright 2015 Russell Smith <mr-russ@smith2001.net>
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 namespace core\session;
29 defined('MOODLE_INTERNAL') || die();
32 * Redis based session handler.
34 * The default Redis session handler does not handle locking in 2.2.7, so we have written a php session handler
35 * that uses locking. The places where locking is used was modeled from the memcached code that is used in Moodle
36 * https://github.com/php-memcached-dev/php-memcached/blob/master/php_memcached_session.c
39 * @copyright 2016 Russell Smith
40 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
42 class redis extends handler {
43 /** @var string $host save_path string */
45 /** @var int $port The port to connect to */
46 protected $port = 6379;
47 /** @var int $database the Redis database to store sesions in */
48 protected $database = 0;
49 /** @var array $servers list of servers parsed from save_path */
50 protected $prefix = '';
51 /** @var int $acquiretimeout how long to wait for session lock in seconds */
52 protected $acquiretimeout = 120;
54 * @var int $lockexpire how long to wait in seconds before expiring the lock automatically
55 * so that other requests may continue execution, ignored if PECL redis is below version 2.2.0.
57 protected $lockexpire = 7200;
59 /** @var Redis Connection */
60 protected $connection = null;
62 /** @var array $locks List of currently held locks by this page. */
63 protected $locks = array();
66 * Create new instance of handler.
68 public function __construct() {
71 if (isset($CFG->session_redis_host)) {
72 $this->host = $CFG->session_redis_host;
75 if (isset($CFG->session_redis_port)) {
76 $this->port = (int)$CFG->session_redis_port;
79 if (isset($CFG->session_redis_database)) {
80 $this->database = (int)$CFG->session_redis_database;
83 if (isset($CFG->session_redis_prefix)) {
84 $this->prefix = $CFG->session_redis_prefix;
87 if (isset($CFG->session_redis_acquire_lock_timeout)) {
88 $this->acquiretimeout = (int)$CFG->session_redis_acquire_lock_timeout;
91 if (isset($CFG->session_redis_lock_expire)) {
92 $this->lockexpire = (int)$CFG->session_redis_lock_expire;
99 * @return bool success
101 public function start() {
102 $result = parent::start();
108 * Init session handler.
110 public function init() {
111 if (!extension_loaded('redis')) {
112 throw new exception('sessionhandlerproblem', 'error', '', null, 'redis extension is not loaded');
115 if (empty($this->host)) {
116 throw new exception('sessionhandlerproblem', 'error', '', null,
117 '$CFG->session_redis_host must be specified in config.php');
120 // The session handler requires a version of Redis with the SETEX command (at least 2.0).
121 $version = phpversion('Redis');
122 if (!$version or version_compare($version, '2.0') <= 0) {
123 throw new exception('sessionhandlerproblem', 'error', '', null, 'redis extension version must be at least 2.0');
126 $this->connection = new \Redis();
128 $result = session_set_save_handler(array($this, 'handler_open'),
129 array($this, 'handler_close'),
130 array($this, 'handler_read'),
131 array($this, 'handler_write'),
132 array($this, 'handler_destroy'),
133 array($this, 'handler_gc'));
135 throw new exception('redissessionhandlerproblem', 'error');
139 // One second timeout was chosen as it is long for connection, but short enough for a user to be patient.
140 if (!$this->connection->connect($this->host, $this->port, 1)) {
141 throw new RedisException('Unable to connect to host.');
143 if (!$this->connection->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_PHP)) {
144 throw new RedisException('Unable to set Redis PHP Serializer option.');
147 if ($this->prefix !== '') {
148 // Use custom prefix on sessions.
149 if (!$this->connection->setOption(\Redis::OPT_PREFIX, $this->prefix)) {
150 throw new RedisException('Unable to set Redis Prefix option.');
153 if ($this->database !== 0) {
154 if (!$this->connection->select($this->database)) {
155 throw new RedisException('Unable to select Redis database '.$this->database.'.');
158 $this->connection->ping();
160 } catch (RedisException $e) {
161 error_log('Failed to connect to redis at '.$this->host.':'.$this->port.', error returned was: '.$e->getMessage());
167 * Update our session search path to include session name when opened.
169 * @param string $savepath unused session save path. (ignored)
170 * @param string $sessionname Session name for this session. (ignored)
171 * @return bool true always as we will succeed.
173 public function handler_open($savepath, $sessionname) {
178 * Close the session completely. We also remove all locks we may have obtained that aren't expired.
180 * @return bool true on success. false on unable to unlock sessions.
182 public function handler_close() {
184 foreach ($this->locks as $id => $expirytime) {
185 if ($expirytime > $this->time()) {
186 $this->unlock_session($id);
188 unset($this->locks[$id]);
190 } catch (RedisException $e) {
191 error_log('Failed talking to redis: '.$e->getMessage());
198 * Read the session data from storage
200 * @param string $id The session id to read from storage.
201 * @return string The session data for PHP to process.
203 * @throws RedisException when we are unable to talk to the Redis server.
205 public function handler_read($id) {
207 $this->lock_session($id);
208 $sessiondata = $this->connection->get($id);
209 if ($sessiondata === false) {
210 $this->unlock_session($id);
213 $this->connection->expire($id, $this->lockexpire);
214 } catch (RedisException $e) {
215 error_log('Failed talking to redis: '.$e->getMessage());
222 * Write the serialized session data to our session store.
224 * @param string $id session id to write.
225 * @param string $data session data
226 * @return bool true on write success, false on failure
228 public function handler_write($id, $data) {
229 if (is_null($this->connection)) {
230 // The session has already been closed, don't attempt another write.
231 error_log('Tried to write session: '.$id.' before open or after close.');
235 // We do not do locking here because memcached doesn't. Also
236 // PHP does open, read, destroy, write, close. When a session doesn't exist.
237 // There can be race conditions on new sessions racing each other but we can
238 // address that in the future.
240 $this->connection->setex($id, $this->lockexpire, $data);
241 } catch (RedisException $e) {
242 error_log('Failed talking to redis: '.$e->getMessage());
249 * Handle destroying a session.
251 * @param string $id the session id to destroy.
252 * @return bool true if the session was deleted, false otherwise.
254 public function handler_destroy($id) {
256 $this->connection->del($id);
257 $this->unlock_session($id);
258 } catch (RedisException $e) {
259 error_log('Failed talking to redis: '.$e->getMessage());
267 * Garbage collect sessions. We don't we any as Redis does it for us.
269 * @param integer $maxlifetime All sessions older than this should be removed.
270 * @return bool true, as Redis handles expiry for us.
272 public function handler_gc($maxlifetime) {
279 * @param string $id Session id to be unlocked.
281 protected function unlock_session($id) {
282 if (isset($this->locks[$id])) {
283 $this->connection->del($id.".lock");
284 unset($this->locks[$id]);
289 * Obtain a session lock so we are the only one using it at the moent.
291 * @param string $id The session id to lock.
292 * @return bool true when session was locked, exception otherwise.
293 * @throws exception When we are unable to obtain a session lock.
295 protected function lock_session($id) {
296 $lockkey = $id.".lock";
298 $haslock = isset($this->locks[$id]) && $this->time() < $this->locks[$id];
299 $startlocktime = $this->time();
301 /* To be able to ensure sessions don't write out of order we must obtain an exclusive lock
302 * on the session for the entire time it is open. If another AJAX call, or page is using
303 * the session then we just wait until it finishes before we can open the session.
306 $haslock = $this->connection->setnx($lockkey, '1');
308 usleep(rand(100000, 1000000));
309 if ($this->time() > $startlocktime + $this->acquiretimeout) {
310 // This is a fatal error, better inform users.
311 // It should not happen very often - all pages that need long time to execute
312 // should close session immediately after access control checks.
313 error_log('Cannot obtain session lock for sid: '.$id.' within '.$this->acquiretimeout.
314 '. It is likely another page has a long session lock, or the session lock was never released.');
315 throw new exception("Unable to obtain session lock");
318 $this->locks[$id] = $this->time() + $this->lockexpire;
319 $this->connection->expire($lockkey, $this->lockexpire);
326 * Return the current time.
328 * @return int the current time as a unixtimestamp.
330 protected function time() {
335 * Check the backend contains data for this session id.
337 * Note: this is intended to be called from manager::session_exists() only.
340 * @return bool true if session found.
342 public function session_exists($sid) {
343 if (!$this->connection) {
348 return $this->connection->exists($sid);
349 } catch (RedisException $e) {
355 * Kill all active sessions, the core sessions table is purged afterwards.
357 public function kill_all_sessions() {
359 if (!$this->connection) {
363 $rs = $DB->get_recordset('sessions', array(), 'id DESC', 'id, sid');
364 foreach ($rs as $record) {
365 $this->handler_destroy($record->sid);
371 * Kill one session, the session record is removed afterwards.
375 public function kill_session($sid) {
376 if (!$this->connection) {
380 $this->handler_destroy($sid);