dmemcache.inc 9.35 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
<?php
// $Id$

/*
 * Core dmemcache functions required by:
 *   memcache.inc
 *   memcache.db.inc
 *   session-memcache.inc
 *   session-memcache.db.inc
 */

global $_memcache_statistics;
$_memcache_statistics = array('get' => array(), 'set' => array(), 'hit' => array());

/*
 * A memcache API for Drupal.
 */

/**
 *  Place an item into memcache
 *
 * @param $key The string with with you will retrieve this item later.
 * @param $value The item to be stored.
 * @param $exp Parameter expire is expiration time in seconds. If it's 0, the item never expires
 *   (but memcached server doesn't guarantee this item to be stored all the time, it could be
 *   deleted from the cache to make place for other items).
 * @param $bin The name of the Drupal subsystem that is making this call. Examples could be
 *   'cache', 'alias', 'taxonomy term' etc. It is possible to map different $bin values to
 *   different memcache servers.
 *
 * @return bool
 */
33
function dmemcache_set($key, $value, $exp = 0, $bin = 'cache', $mc = NULL) {
34 35 36
  global $_memcache_statistics;
  $_memcache_statistics['set'][] = $key;
  $_memcache_statistics['bins'][] = $bin;
37
  if ($mc || ($mc = dmemcache_object($bin))) {
38
    $full_key = dmemcache_key($key, $bin);
39
    error_log("setting: ". $full_key . gmdate('c') . "\n", 3, '/tmp/log');
40 41 42 43
    if (class_exists('Memcached') && !$mc->set($full_key, $value, $exp)) {
      return FALSE;
    }
    else if (class_exists('Memcache') && !$mc->set($full_key, $value, MEMCACHE_COMPRESSED, $exp)) {
44
      return FALSE;
45 46 47 48 49 50 51 52
    }
    else {
      return TRUE;
    }
  }
  return FALSE;
}

53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
function dmemcache_add($key, $value, $exp = 0, $bin = 'cache', $mc = NULL, $flag = FALSE) {
  global $_memcache_statistics;
  $_memcache_statistics['add'][] = $key;
  $_memcache_statistics['bins'][] = $bin;
  if ($mc || ($mc = dmemcache_object($bin))) {
    $full_key = dmemcache_key($key, $bin);
    error_log("setting: ". $full_key . gmdate('c') . "\n", 3, '/tmp/log');
    if (class_exists('Memcached')) {
      return $mc->add($key, $value, $exp);
    }
    else {
      return $mc->add($key, $value, $flag, $exp);
    }
  }
}

69 70 71 72 73 74 75 76
/**
 * Retrieve a value from the cache.
 *
 * @param $key The key with which the item was stored.
 * @param $bin The bin in which the item was stored.
 *
 * @return The item which was originally saved or FALSE
 */
77
function dmemcache_get($key, $bin = 'cache', $mc = NULL) {
78 79 80
  global $_memcache_statistics;
  $_memcache_statistics['get'][] = $key;
  $_memcache_statistics['bins'][] = $bin;
81
  if ($mc || ($mc = dmemcache_object($bin))) {
82
    $full_key = dmemcache_key($key, $bin);
83
    $result = $mc->get($full_key);
84
    if ($result) {
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
      $_memcache_statistics['hit'][] = $key;
      return $result;
    }
  }
}

/**
 * Retrieve multiple values from the cache.
 *
 * @param $keys The keys with which the items were stored.
 * @param $bin The bin in which the item was stored.
 *
 * @return The item which was originally saved or FALSE
 */
function dmemcache_get_multi($keys, $bin = 'cache', $mc = NULL) {
  global $_memcache_statistics;
  $_memcache_statistics['get'] = array_merge($_memcache_statistics['get'], $keys);
  $_memcache_statistics['bins'][] = $bin;
  $results = array();
  if ($mc || ($mc = dmemcache_object($bin))) {
    if (class_exists('Memcached')) {
      $full_keys = array();
      foreach ($keys as $key => $cid) {
        $full_keys[] = dmemcache_key($cid, $bin);
109
      }
110 111 112 113 114 115 116 117 118 119
      $results = $mc->getMulti($full_keys);
    }
    else {
      // simulate multi-get
      foreach ($keys as $key => $cid) {
        $full_key = dmemcache_key($cid, $bin);
        if ($result = $mc->get($full_key)) {
          $results[$cid] = $result;
          $_memcache_statistics['hit'][] = $cid;
        }
120
      }
121 122
    }
  }
123
  return $results;
124 125 126 127 128 129 130 131 132 133
}

/**
 * Deletes an item from the cache.
 *
 * @param $key The key with which the item was stored.
 * @param $bin The bin in which the item was stored.
 *
 * @return Returns TRUE on success or FALSE on failure.
 */
134 135
function dmemcache_delete($key, $bin = 'cache', $mc = NULL) {
  if ($mc || ($mc = dmemcache_object($bin))) {
136
    $full_key = dmemcache_key($key, $bin);
137
    return $mc->delete($full_key);
138 139 140 141 142 143 144 145 146 147 148 149 150 151
  }
  return FALSE;
}

/**
 * Immediately invalidates all existing items. dmemcache_flush doesn't actually free any
 * resources, it only marks all the items as expired, so occupied memory will be overwritten by
 * new items.
 *
 * @param $bin The bin to flush. Note that this will flush all bins mapped to the same server
 *   as $bin. There is no way at this time to empty just one bin.
 *
 * @return Returns TRUE on success or FALSE on failure.
 */
152 153
function dmemcache_flush($bin = 'cache', $mc = NULL) {
  if ($mc || ($mc = dmemcache_object($bin))) {
154
    return memcache_flush($mc);
155 156 157 158
  }
}

function dmemcache_stats($bin = 'cache', $type = '') {
159 160 161 162 163 164 165 166
  // resolve requests for 'default' type to ''
  if ($type == 'default') {
    $type = '';
  }
  // resolve requests for 'default' bin to 'cache'.
  if ($bin == 'default') {
    $bin = 'cache';
  }
167
  if ($mc = dmemcache_object($bin)) {
168 169 170
    if (class_exists('Memcached')) {
      return $mc->getStats();
    }
171 172
    // The PHP Memcache extension 3.x version throws an error if the stats
    // type is NULL or not in {reset, malloc, slabs, cachedump, items, sizes}.
173
    // If $type is 'default', then no parameter should be passed to the
174 175
    // Memcache memcache_get_extended_stats() function.
    if ($type == 'default' || $type == '') {
176
      return memcache_getExtendedStats($mc);
177 178
    }
    else {
179
      return memcache_getExtendedStats($mc, $type);
180
    }
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
  }
}

/**
 * Returns an Memcache object based on the bin requested. Note that there is
 * nothing preventing developers from calling this function directly to get the
 * Memcache object. Do this if you need functionality not provided by this API
 * or if you need to use legacy code. Otherwise, use the dmemcache (get, set,
 * delete, flush) API functions provided here.
 *
 * @param $bin The bin which is to be used.
 *
 * @param $flush Rebuild the bin/server/cache mapping.
 *
 * @return an Memcache object or FALSE.
 */
function dmemcache_object($bin = NULL, $flush = FALSE) {
  static $memcacheCache = array(), $memcache_servers, $memcache_bins;

  if ($flush) {
    foreach ($memcacheCache as $cluster) {
202
      memcache_close($cluster);
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
    }
    $memcacheCache = array();
  }

  if (empty($memcacheCache) || empty($memcacheCache[$bin])) {
    // $memcache_servers and $memcache_bins originate from settings.php.
    // $memcache_servers_custom and $memcache_bins_custom get set by
    // memcache.module. They are then merged into $memcache_servers and
    // $memcache_bins, which are statically cached for performance.
    if (empty($memcache_servers)) {
      // Values from settings.php
      $memcache_servers = variable_get('memcache_servers', array('127.0.0.1:11211' => 'default'));
      $memcache_bins    = variable_get('memcache_bins', array('cache' => 'default'));
    }

    // If there is no cluster for this bin in $memcache_bins, cluster is 'default'.
    $cluster = empty($memcache_bins[$bin]) ? 'default' : $memcache_bins[$bin];

    // If this bin isn't in our $memcache_bins configuration array, and the
    // 'default' cluster is already initialized, map the bin to 'cache' because
    // we always map the 'cache' bin to the 'default' cluster.
    if (empty($memcache_bins[$bin]) && !empty($memcacheCache['cache'])) {
      $memcacheCache[$bin] = &$memcacheCache['cache'];
    }
    else {
      // Create a new Memcache object. Each cluster gets its own Memcache object.
229 230 231 232 233 234 235 236 237 238
      if (class_exists('Memcached')) {
        $memcache = new Memcached;
      }
      else if (class_exists('Memcache')) {
        $memcache = new Memcache;
      }
      else {
        drupal_set_message(t('You must enable the PECL memcached or memcache extension to use memcache.inc.'), 'error');
        return;
      }
239 240 241 242 243 244 245 246 247
      // A variable to track whether we've connected to the first server.
      $init = FALSE;

      // Link all the servers to this cluster.
      foreach ($memcache_servers as $s => $c) {
        if ($c == $cluster) {
          list($host, $port) = explode(':', $s);

          // This is a server that belongs to this cluster.
248 249 250
          if (!class_exists('Memcached') && !$init) {
            // If using PECL memcache extension, use ->connect for first server
            if ($memcache->connect($host, $port)) {
251 252 253 254
              $init = TRUE;
            }
          }
          else {
255 256 257
            if ($memcache->addServer($host, $port) && !$init) {
              $init = TRUE;
            }
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
          }
        }
      }

      if ($init) {
        // Map the current bin with the new Memcache object.
        $memcacheCache[$bin] = $memcache;

        // Now that all the servers have been mapped to this cluster, look for
        // other bins that belong to the cluster and map them too.
        foreach ($memcache_bins as $b => $c) {
          if ($c == $cluster && $b != $bin) {
            // Map this bin and cluster by reference.
            $memcacheCache[$b] = &$memcacheCache[$bin];
          }
        }
      }
    }
  }

  return empty($memcacheCache[$bin]) ? FALSE : $memcacheCache[$bin];
}

function dmemcache_key($key, $bin = 'cache') {
  static $prefix;
  // memcache_key_prefix can be set in settings.php to support site namespaces
  // in a multisite environment.
  if (empty($prefix)) {
    $prefix = variable_get('memcache_key_prefix', '');
  }
  $full_key = ($prefix ? $prefix. '-' : '') . $bin . '-' . $key;
289

290 291
  return urlencode($full_key);
}