Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 3.9.x will end* 10 May 2021 (12 months).
  • Bug fixes for security issues in 3.9.x will end* 8 May 2023 (36 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.

Differences Between: [Versions 39 and 310] [Versions 39 and 311] [Versions 39 and 400] [Versions 39 and 401] [Versions 39 and 402] [Versions 39 and 403]

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   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.
   8  //
   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.
  13  //
  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/>.
  16  
  17  /**
  18   * Redis based session handler.
  19   *
  20   * @package    core
  21   * @copyright  2015 Russell Smith <mr-russ@smith2001.net>
  22   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   */
  24  
  25  namespace core\session;
  26  
  27  use RedisException;
  28  
  29  defined('MOODLE_INTERNAL') || die();
  30  
  31  /**
  32   * Redis based session handler.
  33   *
  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
  37   *
  38   * @package    core
  39   * @copyright  2016 Russell Smith
  40   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  41   */
  42  class redis extends handler {
  43      /** @var string $host save_path string  */
  44      protected $host = '';
  45      /** @var int $port The port to connect to */
  46      protected $port = 6379;
  47      /** @var string $auth redis password  */
  48      protected $auth = '';
  49      /** @var int $database the Redis database to store sesions in */
  50      protected $database = 0;
  51      /** @var array $servers list of servers parsed from save_path */
  52      protected $prefix = '';
  53      /** @var int $acquiretimeout how long to wait for session lock in seconds */
  54      protected $acquiretimeout = 120;
  55      /** @var int $lockretry how long to wait between session lock attempts in ms */
  56      protected $lockretry = 100;
  57      /** @var int $serializer The serializer to use */
  58      protected $serializer = \Redis::SERIALIZER_PHP;
  59      /**
  60       * @var int $lockexpire how long to wait in seconds before expiring the lock automatically
  61       * so that other requests may continue execution, ignored if PECL redis is below version 2.2.0.
  62       */
  63      protected $lockexpire;
  64  
  65      /** @var Redis Connection */
  66      protected $connection = null;
  67  
  68      /** @var array $locks List of currently held locks by this page. */
  69      protected $locks = array();
  70  
  71      /** @var int $timeout How long sessions live before expiring. */
  72      protected $timeout;
  73  
  74      /**
  75       * Create new instance of handler.
  76       */
  77      public function __construct() {
  78          global $CFG;
  79  
  80          if (isset($CFG->session_redis_host)) {
  81              $this->host = $CFG->session_redis_host;
  82          }
  83  
  84          if (isset($CFG->session_redis_port)) {
  85              $this->port = (int)$CFG->session_redis_port;
  86          }
  87  
  88          if (isset($CFG->session_redis_auth)) {
  89              $this->auth = $CFG->session_redis_auth;
  90          }
  91  
  92          if (isset($CFG->session_redis_database)) {
  93              $this->database = (int)$CFG->session_redis_database;
  94          }
  95  
  96          if (isset($CFG->session_redis_prefix)) {
  97              $this->prefix = $CFG->session_redis_prefix;
  98          }
  99  
 100          if (isset($CFG->session_redis_acquire_lock_timeout)) {
 101              $this->acquiretimeout = (int)$CFG->session_redis_acquire_lock_timeout;
 102          }
 103  
 104          if (isset($CFG->session_redis_acquire_lock_retry)) {
 105              $this->lockretry = (int)$CFG->session_redis_acquire_lock_retry;
 106          }
 107  
 108          if (!empty($CFG->session_redis_serializer_use_igbinary) && defined('\Redis::SERIALIZER_IGBINARY')) {
 109              $this->serializer = \Redis::SERIALIZER_IGBINARY; // Set igbinary serializer if phpredis supports it.
 110          }
 111  
 112          // The following configures the session lifetime in redis to allow some
 113          // wriggle room in the user noticing they've been booted off and
 114          // letting them log back in before they lose their session entirely.
 115          $updatefreq = empty($CFG->session_update_timemodified_frequency) ? 20 : $CFG->session_update_timemodified_frequency;
 116          $this->timeout = $CFG->sessiontimeout + $updatefreq + MINSECS;
 117  
 118          $this->lockexpire = $CFG->sessiontimeout;
 119          if (isset($CFG->session_redis_lock_expire)) {
 120              $this->lockexpire = (int)$CFG->session_redis_lock_expire;
 121          }
 122      }
 123  
 124      /**
 125       * Start the session.
 126       *
 127       * @return bool success
 128       */
 129      public function start() {
 130          $result = parent::start();
 131  
 132          return $result;
 133      }
 134  
 135      /**
 136       * Init session handler.
 137       */
 138      public function init() {
 139          if (!extension_loaded('redis')) {
 140              throw new exception('sessionhandlerproblem', 'error', '', null, 'redis extension is not loaded');
 141          }
 142  
 143          if (empty($this->host)) {
 144              throw new exception('sessionhandlerproblem', 'error', '', null,
 145                      '$CFG->session_redis_host must be specified in config.php');
 146          }
 147  
 148          // The session handler requires a version of Redis with the SETEX command (at least 2.0).
 149          $version = phpversion('Redis');
 150          if (!$version or version_compare($version, '2.0') <= 0) {
 151              throw new exception('sessionhandlerproblem', 'error', '', null, 'redis extension version must be at least 2.0');
 152          }
 153  
 154          $this->connection = new \Redis();
 155  
 156          $result = session_set_save_handler(array($this, 'handler_open'),
 157              array($this, 'handler_close'),
 158              array($this, 'handler_read'),
 159              array($this, 'handler_write'),
 160              array($this, 'handler_destroy'),
 161              array($this, 'handler_gc'));
 162          if (!$result) {
 163              throw new exception('redissessionhandlerproblem', 'error');
 164          }
 165  
 166          // MDL-59866: Add retries for connections (up to 5 times) to make sure it goes through.
 167          $counter = 1;
 168          $maxnumberofretries = 5;
 169  
 170          while ($counter <= $maxnumberofretries) {
 171  
 172              try {
 173  
 174                  $delay = rand(100000, 500000);
 175  
 176                  // One second timeout was chosen as it is long for connection, but short enough for a user to be patient.
 177                  if (!$this->connection->connect($this->host, $this->port, 1, null, $delay)) {
 178                      throw new RedisException('Unable to connect to host.');
 179                  }
 180  
 181                  if ($this->auth !== '') {
 182                      if (!$this->connection->auth($this->auth)) {
 183                          throw new RedisException('Unable to authenticate.');
 184                      }
 185                  }
 186  
 187                  if (!$this->connection->setOption(\Redis::OPT_SERIALIZER, $this->serializer)) {
 188                      throw new RedisException('Unable to set Redis PHP Serializer option.');
 189                  }
 190  
 191                  if ($this->prefix !== '') {
 192                      // Use custom prefix on sessions.
 193                      if (!$this->connection->setOption(\Redis::OPT_PREFIX, $this->prefix)) {
 194                          throw new RedisException('Unable to set Redis Prefix option.');
 195                      }
 196                  }
 197                  if ($this->database !== 0) {
 198                      if (!$this->connection->select($this->database)) {
 199                          throw new RedisException('Unable to select Redis database '.$this->database.'.');
 200                      }
 201                  }
 202                  $this->connection->ping();
 203                  return true;
 204              } catch (RedisException $e) {
 205                  $logstring = "Failed to connect (try {$counter} out of {$maxnumberofretries}) to redis ";
 206                  $logstring .= "at {$this->host}:{$this->port}, error returned was: {$e->getMessage()}";
 207  
 208                  debugging($logstring);
 209              }
 210  
 211              $counter++;
 212  
 213              // Introduce a random sleep between 100ms and 500ms.
 214              usleep(rand(100000, 500000));
 215          }
 216  
 217          // We have exhausted our retries, time to give up.
 218          if (isset($logstring)) {
 219              throw new RedisException($logstring);
 220          }
 221      }
 222  
 223      /**
 224       * Update our session search path to include session name when opened.
 225       *
 226       * @param string $savepath  unused session save path. (ignored)
 227       * @param string $sessionname Session name for this session. (ignored)
 228       * @return bool true always as we will succeed.
 229       */
 230      public function handler_open($savepath, $sessionname) {
 231          return true;
 232      }
 233  
 234      /**
 235       * Close the session completely. We also remove all locks we may have obtained that aren't expired.
 236       *
 237       * @return bool true on success.  false on unable to unlock sessions.
 238       */
 239      public function handler_close() {
 240          try {
 241              foreach ($this->locks as $id => $expirytime) {
 242                  if ($expirytime > $this->time()) {
 243                      $this->unlock_session($id);
 244                  }
 245                  unset($this->locks[$id]);
 246              }
 247          } catch (RedisException $e) {
 248              error_log('Failed talking to redis: '.$e->getMessage());
 249              return false;
 250          }
 251  
 252          return true;
 253      }
 254      /**
 255       * Read the session data from storage
 256       *
 257       * @param string $id The session id to read from storage.
 258       * @return string The session data for PHP to process.
 259       *
 260       * @throws RedisException when we are unable to talk to the Redis server.
 261       */
 262      public function handler_read($id) {
 263          try {
 264              if ($this->requires_write_lock()) {
 265                  $this->lock_session($id);
 266              }
 267              $sessiondata = $this->connection->get($id);
 268              if ($sessiondata === false) {
 269                  if ($this->requires_write_lock()) {
 270                      $this->unlock_session($id);
 271                  }
 272                  return '';
 273              }
 274              $this->connection->expire($id, $this->timeout);
 275          } catch (RedisException $e) {
 276              error_log('Failed talking to redis: '.$e->getMessage());
 277              throw $e;
 278          }
 279          return $sessiondata;
 280      }
 281  
 282      /**
 283       * Write the serialized session data to our session store.
 284       *
 285       * @param string $id session id to write.
 286       * @param string $data session data
 287       * @return bool true on write success, false on failure
 288       */
 289      public function handler_write($id, $data) {
 290          if (is_null($this->connection)) {
 291              // The session has already been closed, don't attempt another write.
 292              error_log('Tried to write session: '.$id.' before open or after close.');
 293              return false;
 294          }
 295  
 296          // We do not do locking here because memcached doesn't.  Also
 297          // PHP does open, read, destroy, write, close. When a session doesn't exist.
 298          // There can be race conditions on new sessions racing each other but we can
 299          // address that in the future.
 300          try {
 301              $this->connection->setex($id, $this->timeout, $data);
 302          } catch (RedisException $e) {
 303              error_log('Failed talking to redis: '.$e->getMessage());
 304              return false;
 305          }
 306          return true;
 307      }
 308  
 309      /**
 310       * Handle destroying a session.
 311       *
 312       * @param string $id the session id to destroy.
 313       * @return bool true if the session was deleted, false otherwise.
 314       */
 315      public function handler_destroy($id) {
 316          try {
 317              $this->connection->del($id);
 318              $this->unlock_session($id);
 319          } catch (RedisException $e) {
 320              error_log('Failed talking to redis: '.$e->getMessage());
 321              return false;
 322          }
 323  
 324          return true;
 325      }
 326  
 327      /**
 328       * Garbage collect sessions.  We don't we any as Redis does it for us.
 329       *
 330       * @param integer $maxlifetime All sessions older than this should be removed.
 331       * @return bool true, as Redis handles expiry for us.
 332       */
 333      public function handler_gc($maxlifetime) {
 334          return true;
 335      }
 336  
 337      /**
 338       * Unlock a session.
 339       *
 340       * @param string $id Session id to be unlocked.
 341       */
 342      protected function unlock_session($id) {
 343          if (isset($this->locks[$id])) {
 344              $this->connection->del($id.".lock");
 345              unset($this->locks[$id]);
 346          }
 347      }
 348  
 349      /**
 350       * Obtain a session lock so we are the only one using it at the moment.
 351       *
 352       * @param string $id The session id to lock.
 353       * @return bool true when session was locked, exception otherwise.
 354       * @throws exception When we are unable to obtain a session lock.
 355       */
 356      protected function lock_session($id) {
 357          $lockkey = $id.".lock";
 358  
 359          $haslock = isset($this->locks[$id]) && $this->time() < $this->locks[$id];
 360          $startlocktime = $this->time();
 361  
 362          /* To be able to ensure sessions don't write out of order we must obtain an exclusive lock
 363           * on the session for the entire time it is open.  If another AJAX call, or page is using
 364           * the session then we just wait until it finishes before we can open the session.
 365           */
 366  
 367          // Store the current host, process id and the request URI so it's easy to track who has the lock.
 368          $hostname = gethostname();
 369          if ($hostname === false) {
 370              $hostname = 'UNKNOWN HOST';
 371          }
 372          $pid = getmypid();
 373          if ($pid === false) {
 374              $pid = 'UNKNOWN';
 375          }
 376          $uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : 'unknown uri';
 377  
 378          $whoami = "[pid {$pid}] {$hostname}:$uri";
 379  
 380          while (!$haslock) {
 381  
 382              $haslock = $this->connection->setnx($lockkey, $whoami);
 383  
 384              if ($haslock) {
 385                  $this->locks[$id] = $this->time() + $this->lockexpire;
 386                  $this->connection->expire($lockkey, $this->lockexpire);
 387                  return true;
 388              }
 389  
 390              if ($this->time() > $startlocktime + $this->acquiretimeout) {
 391                  // This is a fatal error, better inform users.
 392                  // It should not happen very often - all pages that need long time to execute
 393                  // should close session immediately after access control checks.
 394                  $whohaslock = $this->connection->get($lockkey);
 395                  // @codingStandardsIgnoreStart
 396                  error_log("Cannot obtain session lock for sid: $id within $this->acquiretimeout seconds. " .
 397                      "It is likely another page ($whohaslock) has a long session lock, or the session lock was never released.");
 398                  // @codingStandardsIgnoreEnd
 399                  throw new exception("Unable to obtain session lock");
 400              }
 401  
 402              if ($this->time() < $startlocktime + 5) {
 403                  // We want a random delay to stagger the polling load. Ideally
 404                  // this delay should be a fraction of the average response
 405                  // time. If it is too small we will poll too much and if it is
 406                  // too large we will waste time waiting for no reason. 100ms is
 407                  // the default starting point.
 408                  $delay = rand($this->lockretry, $this->lockretry * 1.1);
 409              } else {
 410                  // If we don't get a lock within 5 seconds then there must be a
 411                  // very long lived process holding the lock so throttle back to
 412                  // just polling roughly once a second.
 413                  $delay = rand(1000, 1100);
 414              }
 415  
 416              usleep($delay * 1000);
 417          }
 418      }
 419  
 420      /**
 421       * Return the current time.
 422       *
 423       * @return int the current time as a unixtimestamp.
 424       */
 425      protected function time() {
 426          return time();
 427      }
 428  
 429      /**
 430       * Check the backend contains data for this session id.
 431       *
 432       * Note: this is intended to be called from manager::session_exists() only.
 433       *
 434       * @param string $sid
 435       * @return bool true if session found.
 436       */
 437      public function session_exists($sid) {
 438          if (!$this->connection) {
 439              return false;
 440          }
 441  
 442          try {
 443              return !empty($this->connection->exists($sid));
 444          } catch (RedisException $e) {
 445              return false;
 446          }
 447      }
 448  
 449      /**
 450       * Kill all active sessions, the core sessions table is purged afterwards.
 451       */
 452      public function kill_all_sessions() {
 453          global $DB;
 454          if (!$this->connection) {
 455              return;
 456          }
 457  
 458          $rs = $DB->get_recordset('sessions', array(), 'id DESC', 'id, sid');
 459          foreach ($rs as $record) {
 460              $this->handler_destroy($record->sid);
 461          }
 462          $rs->close();
 463      }
 464  
 465      /**
 466       * Kill one session, the session record is removed afterwards.
 467       *
 468       * @param string $sid
 469       */
 470      public function kill_session($sid) {
 471          if (!$this->connection) {
 472              return;
 473          }
 474  
 475          $this->handler_destroy($sid);
 476      }
 477  }