Skip to content

Commit

Permalink
Add support for session storage using memcache
Browse files Browse the repository at this point in the history
  • Loading branch information
thomascube committed Apr 25, 2011
1 parent 926948e commit 63e9927
Show file tree
Hide file tree
Showing 3 changed files with 170 additions and 31 deletions.
9 changes: 9 additions & 0 deletions config/main.inc.php.dist
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,15 @@ $rcmail_config['session_lifetime'] = 10;
// session domain: .example.org
$rcmail_config['session_domain'] = '';

// Backend to use for session storage. Can either be 'db' (default) or 'memcache'
// If set to memcache, a list of servers need to be specified in 'memcache_hosts'
// Make sure the Memcache extension (http://pecl.php.net/package/memcache) version >= 2.0.0 is installed
$rcmail_config['session_storage'] = 'db';

// Use these hosts for accessing memcached
// Define any number of hosts in the form hostname:port
$rcmail_config['memcache_hosts'] = null; // e.g. array( 'localhost:11211', '192.168.1.12:11211' );

// check client IP in session athorization
$rcmail_config['ip_check'] = false;

Expand Down
7 changes: 3 additions & 4 deletions program/include/rcmail.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
| program/include/rcmail.php |
| |
| This file is part of the Roundcube Webmail client |
| Copyright (C) 2008-2010, The Roundcube Dev Team |
| Copyright (C) 2008-2011, The Roundcube Dev Team |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
Expand Down Expand Up @@ -570,13 +570,12 @@ public function session_init()
if (session_id())
return;

$lifetime = $this->config->get('session_lifetime', 0) * 60;

// set session domain
if ($domain = $this->config->get('session_domain')) {
ini_set('session.cookie_domain', $domain);
}
// set session garbage collecting time according to session_lifetime
$lifetime = $this->config->get('session_lifetime', 0) * 60;
if ($lifetime) {
ini_set('session.gc_maxlifetime', $lifetime * 2);
}
Expand All @@ -588,7 +587,7 @@ public function session_init()
ini_set('session.serialize_handler', 'php');

// use database for storing session data
$this->session = new rcube_session($this->get_dbh(), $lifetime);
$this->session = new rcube_session($this->get_dbh(), $this->config);

$this->session->register_gc_handler('rcmail_temp_gc');
if ($this->config->get('enable_caching'))
Expand Down
185 changes: 158 additions & 27 deletions program/include/rcube_session.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,26 +43,59 @@ class rcube_session
private $secret = '';
private $ip_check = false;
private $keep_alive = 0;
private $memcache;

/**
* Default constructor
*/
public function __construct($db, $lifetime=60)
public function __construct($db, $config)
{
$this->db = $db;
$this->start = microtime(true);
$this->ip = $_SERVER['REMOTE_ADDR'];

$lifetime = $config->get('session_lifetime', 1) * 60;
$this->set_lifetime($lifetime);

// set custom functions for PHP session management
session_set_save_handler(
array($this, 'open'),
array($this, 'close'),
array($this, 'read'),
array($this, 'write'),
array($this, 'destroy'),
array($this, 'gc'));
// use memcache backend
if ($config->get('session_storage', 'db') == 'memcache') {
$this->memcache = new Memcache;
$mc_available = 0;
foreach ($config->get('memcache_hosts', array()) as $host) {
list($host, $port) = explode(':', $host);
if (!$port) $port = 11211;
// add server and attempt to connect if not already done yet
if ($this->memcache->addServer($host, $port) && !$mc_available)
$mc_available += intval($this->memcache->connect($host, $port));
}

// set custom functions for PHP session management if memcache is available
if ($mc_available) {
session_set_save_handler(
array($this, 'open'),
array($this, 'close'),
array($this, 'mc_read'),
array($this, 'mc_write'),
array($this, 'mc_destroy'),
array($this, 'rcube_gc'));
}
else {
raise_error(array('code' => 604, 'type' => 'db',
'line' => __LINE__, 'file' => __FILE__,
'message' => "Failed to connect to memcached. Please check configuration"),
true, true);
}
}
else {
// set custom functions for PHP session management
session_set_save_handler(
array($this, 'open'),
array($this, 'close'),
array($this, 'db_read'),
array($this, 'db_write'),
array($this, 'db_destroy'),
array($this, 'db_gc'));
}
}


Expand All @@ -78,8 +111,24 @@ public function close()
}


// read session data
public function read($key)
/**
* Delete session data for the given key
*
* @param string Session ID
*/
public function destroy($key)
{
return $this->memcache ? $this->mc_destroy($key) : $this->db_destroy($key);
}


/**
* Read session data from database
*
* @param string Session ID
* @return string Session vars
*/
public function db_read($key)
{
$sql_result = $this->db->query(
sprintf("SELECT vars, ip, %s AS changed FROM %s WHERE sess_id = ?",
Expand Down Expand Up @@ -108,7 +157,7 @@ public function read($key)
* @param string Serialized session vars
* @return boolean True on success
*/
public function write($key, $vars)
public function db_write($key, $vars)
{
$ts = microtime(true);
$now = $this->db->fromunixtime((int)$ts);
Expand All @@ -121,17 +170,8 @@ public function write($key, $vars)
}

if ($oldvars !== false) {
$a_oldvars = $this->unserialize($oldvars);
if (is_array($a_oldvars)) {
foreach ((array)$this->unsets as $k)
unset($a_oldvars[$k]);

$newvars = $this->serialize(array_merge(
(array)$a_oldvars, (array)$this->unserialize($vars)));
}
else
$newvars = $vars;

$newvars = $this->_fixvars($vars, $oldvars);

if ($newvars !== $oldvars) {
$this->db->query(
sprintf("UPDATE %s SET vars=?, changed=%s WHERE sess_id=?",
Expand All @@ -153,6 +193,28 @@ public function write($key, $vars)
$this->unsets = array();
return true;
}


private function _fixvars($vars, $oldvars)
{
$ts = microtime(true);

if ($oldvars !== false) {
$a_oldvars = $this->unserialize($oldvars);
if (is_array($a_oldvars)) {
foreach ((array)$this->unsets as $k)
unset($a_oldvars[$k]);

$newvars = $this->serialize(array_merge(
(array)$a_oldvars, (array)$this->unserialize($vars)));
}
else
$newvars = $vars;
}

$this->unsets = array();
return $newvars;
}


/**
Expand All @@ -161,7 +223,7 @@ public function write($key, $vars)
* @param string Session ID
* @return boolean True on success
*/
public function destroy($key)
public function db_destroy($key)
{
$this->db->query(
sprintf("DELETE FROM %s WHERE sess_id = ?", get_table_name('session')),
Expand All @@ -177,20 +239,89 @@ public function destroy($key)
* @param string Session lifetime in seconds
* @return boolean True on success
*/
public function gc($maxlifetime)
public function db_gc($maxlifetime)
{
// just delete all expired sessions
$this->db->query(
sprintf("DELETE FROM %s WHERE changed < %s",
get_table_name('session'), $this->db->fromunixtime(time() - $maxlifetime)));

foreach ($this->gc_handlers as $fct)
$fct();
$this->rcube_gc();

return true;
}


/**
* Read session data from memcache
*
* @param string Session ID
* @return string Session vars
*/
public function mc_read($key)
{
if ($value = $this->memcache->get($key)) {
$arr = unserialize($value);
$this->changed = $arr['changed'];
$this->ip = $arr['ip'];
$this->vars = $arr['vars'];
$this->key = $key;

if (!empty($this->vars))
return $this->vars;
}

return false;
}

/**
* Save session data.
* handler for session_read()
*
* @param string Session ID
* @param string Serialized session vars
* @return boolean True on success
*/
public function mc_write($key, $vars)
{
$ts = microtime(true);

// use internal data for fast requests (up to 0.5 sec.)
if ($key == $this->key && $ts - $this->start < 0.5)
$oldvars = $this->vars;
else // else read data again
$oldvars = $this->mc_read($key);

$newvars = $oldvars !== false ? $this->_fixvars($vars, $oldvars) : $vars;

if ($newvars !== $oldvars || $ts - $this->changed > $this->lifetime / 2)
return $this->memcache->set($key, serialize(array('changed' => time(), 'ip' => $this->ip, 'vars' => $newvars)), MEMCACHE_COMPRESSED, $this->lifetime);

return true;
}

/**
* Handler for session_destroy() with memcache backend
*
* @param string Session ID
* @return boolean True on success
*/
public function mc_destroy($key)
{
return $this->memcache->delete($key);
}


/**
* Execute registered garbage collector routines
*/
public function rcube_gc()
{
foreach ($this->gc_handlers as $fct)
$fct();
}


/**
* Cleanup session data before saving
*/
Expand Down

0 comments on commit 63e9927

Please sign in to comment.