dmemcache.inc 41.8 KB
Newer Older
1 2
<?php

3 4 5 6 7
/**
 * @file
 * A memcache API for Drupal.
 *
 * This file contains core dmemcache functions required by:
8
 *   memcache.inc
9 10
 *   memcache-lock.inc
 *   memcache-lock-code.inc
11 12
 */

13 14
define('MEMCACHED_E2BIG', 37);

15 16
global $_dmemcache_stats;
$_dmemcache_stats = array('all' => array(), 'ops' => array());
17 18

/**
19
 * Place an item into memcache.
20
 *
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
 * @param string $key
 *   The string with which you will retrieve this item later.
 * @param mixed $value
 *   The item to be stored.
 * @param int $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 string $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.
 * @param object $mc
 *   Optionally pass in the memcache object.  Normally this value is determined
 *   automatically based on the bin the object is being stored to.
37 38
 *
 * @return bool
39
 *   TRUE on succes, FALSE otherwise.
40
 */
41
function dmemcache_set($key, $value, $exp = 0, $bin = 'cache', $mc = NULL) {
42 43
  $collect_stats = dmemcache_stats_init();

44
  $full_key = dmemcache_key($key, $bin);
45 46

  $rc = FALSE;
47
  if ($mc || ($mc = dmemcache_object($bin))) {
48
    if ($mc instanceof Memcached) {
49
      $rc = $mc->set($full_key, $value, $exp);
50 51 52 53 54 55 56
      if (empty($rc)) {
        // If there was a MEMCACHED_E2BIG error, split the value into pieces
        // and cache them individually.
        if ($mc->getResultCode() == MEMCACHED_E2BIG) {
          $rc = _dmemcache_set_pieces($key, $value, $exp, $bin, $mc);
        }
      }
57 58
    }
    else {
59 60 61 62 63
      // The PECL Memcache library throws an E_NOTICE level error, which
      // $php_errormsg doesn't catch, so we need to log it ourselves.
      // Catch it with our own error handler.
      drupal_static_reset('_dmemcache_error_handler');
      set_error_handler('_dmemcache_error_handler');
64
      $rc = $mc->set($full_key, $value, MEMCACHE_COMPRESSED, $exp);
65 66 67 68 69 70 71 72 73 74
      // Restore the Drupal error handler.
      restore_error_handler();
      if (empty($rc)) {
        // If the object was too big, split the value into pieces and cache
        // them individually.
        $dmemcache_errormsg = &drupal_static('_dmemcache_error_handler');
        if (!empty($dmemcache_errormsg) && (strpos($dmemcache_errormsg, 'SERVER_ERROR object too large for cache') !== FALSE || strpos($dmemcache_errormsg, 'SERVER_ERROR out of memory storing object') !== FALSE)) {
          $rc = _dmemcache_set_pieces($key, $value, $exp, $bin, $mc);
        }
      }
75 76
    }
  }
77 78 79 80 81

  if ($collect_stats) {
    dmemcache_stats_write('set', $bin, array($full_key => $rc));
  }

82
  _dmemcache_write_debug('set', $bin, $full_key, $rc);
83

84
  return $rc;
85 86
}

87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
/**
 * A temporary error handler which keeps track of the most recent error.
 */
function _dmemcache_error_handler($errno, $errstr) {
  $dmemcache_errormsg = &drupal_static(__FUNCTION__);
  $dmemcache_errormsg = $errstr;
  return TRUE;
}

/**
 *  Split a large item into pieces and place them into memcache
 *
 * @param string $key
 *   The string with which you will retrieve this item later.
 * @param mixed $value
 *   The item to be stored.
 * @param int $exp
 *   (optional) 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 string $bin
 *   (optional) 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.
 * @param object $mc
 *   (optional) The memcache object. Normally this value is
 *   determined automatically based on the bin the object is being stored to.
 *
 * @return bool
 */
function _dmemcache_set_pieces($key, $value, $exp = 0, $bin = 'cache', $mc = NULL) {
  static $recursion = 0;
  if (!empty($value->multi_part_data) || !empty($value->multi_part_pieces)) {
    // Prevent an infinite loop.
    return FALSE;
  }

  // Recursion happens when __dmemcache_piece_cache outgrows the largest
  // memcache slice (1 MiB by default) -- prevent an infinite loop and later
  // generate a watchdog error.
  if ($recursion) {
    return FALSE;
  }
  $recursion++;

  $full_key = dmemcache_key($key);

  // Cache the name of this key so if it is deleted later we know to also
  // delete the cache pieces.
  if (!dmemcache_piece_cache_set($full_key, $exp)) {
    // We're caching a LOT of large items. Our piece_cache has exceeded the
    // maximum memcache object size (default of 1 MiB).
    $piece_cache = &drupal_static('dmemcache_piece_cache', array());
    register_shutdown_function('watchdog', 'memcache', 'Too many over-sized cache items (!count) has caused the dmemcache_piece_cache to exceed the maximum memcache object size (default of 1 MiB). Now relying on memcache auto-expiration to eventually clean up over-sized cache pieces upon deletion.', array('!count' => count($piece_cache)), WATCHDOG_ERROR);
  }

  if (variable_get('memcache_log_data_pieces', 2)) {
    timer_start('memcache_split_data');
  }

  // We need to split the item into pieces, so convert it into a string.
  if (is_string($value)) {
    $data = $value;
    $serialized = FALSE;
  }
  else {
153 154
    $serialize_function = dmemcache_serialize();
    $data = $serialize_function($value);
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
    $serialized = TRUE;
  }

  // Account for any metadata stored alongside the data.
  $max_len = variable_get('memcache_data_max_length', 1048576) - (512 + strlen($full_key));
  $pieces = str_split($data, $max_len);

  $piece_count = count($pieces);

  // Create a placeholder item containing data about the pieces.
  $cache = new stdClass;
  // $key gets run through dmemcache_key() later inside dmemcache_set().
  $cache->cid = $key;
  $cache->created = REQUEST_TIME;
  $cache->expire = $exp;
  $cache->data = new stdClass;
  $cache->data->serialized = $serialized;
  $cache->data->piece_count = $piece_count;
  $cache->multi_part_data = TRUE;
  $result = dmemcache_set($cache->cid, $cache, $exp, $bin, $mc);

  // Create a cache item for each piece of data.
  foreach ($pieces as $id => $piece) {
    $cache = new stdClass;
    $cache->cid = _dmemcache_key_piece($key, $id);
    $cache->created = REQUEST_TIME;
    $cache->expire = $exp;
    $cache->data = $piece;
    $cache->multi_part_piece = TRUE;

    $result &= dmemcache_set($cache->cid, $cache, $exp, $bin, $mc);
  }

  if (variable_get('memcache_log_data_pieces', 2) && $piece_count >= variable_get('memcache_log_data_pieces', 2)) {
189 190 191 192 193 194 195
    if (function_exists('format_size')) {
      $data_size = format_size(strlen($data));
    }
    else {
      $data_size = number_format(strlen($data)) . ' byte';
    }
    register_shutdown_function('watchdog', 'memcache', 'Spent !time ms splitting !bytes object into !pieces pieces, cid = !key', array('!time' => timer_read('memcache_split_data'), '!bytes' => $data_size, '!pieces' => $piece_count, '!key' => dmemcache_key($key, $bin)), WATCHDOG_WARNING);
196 197 198 199 200 201 202 203
  }

  $recursion--;

  // TRUE if all pieces were saved correctly.
  return $result;
}

204
/**
205
 * Add an item into memcache.
206
 *
207 208 209 210 211
 * @param string $key
 *   The string with which you will retrieve this item later.
 * @param mixed $value
 *   The item to be stored.
 * @param int $exp
212 213 214
 *   (optional) 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).
215
 * @param string $bin
216
 *   (optional) The name of the Drupal subsystem that is making this call.
217 218
 *   Examples could be 'cache', 'alias', 'taxonomy term' etc. It is possible
 *   to map different $bin values to different memcache servers.
219
 * @param object $mc
220
 *   (optional) The memcache object. Normally this value is
221
 *   determined automatically based on the bin the object is being stored to.
222 223
 * @param bool $flag
 *   (optional) If using the older memcache PECL extension as opposed to the
224 225 226 227 228
 *   newer memcached PECL extension, the MEMCACHE_COMPRESSED flag can be set
 *   to use zlib to store a compressed copy of the item.  This flag option is
 *   completely ignored when using the newer memcached PECL extension.
 *
 * @return bool
229
 *   FALSE if placing the item into memcache failed.
230
 */
231
function dmemcache_add($key, $value, $exp = 0, $bin = 'cache', $mc = NULL, $flag = FALSE) {
232 233
  $collect_stats = dmemcache_stats_init();

234
  $full_key = dmemcache_key($key, $bin);
235 236

  $rc = FALSE;
237
  if ($mc || ($mc = dmemcache_object($bin))) {
238
    if ($mc instanceof Memcached) {
239
      $rc = $mc->add($full_key, $value, $exp);
240 241
    }
    else {
242
      $rc = $mc->add($full_key, $value, $flag, $exp);
243 244
    }
  }
245 246 247 248 249

  if ($collect_stats) {
    dmemcache_stats_write('add', $bin, array($full_key => $rc));
  }

250
  _dmemcache_write_debug('add', $bin, $full_key, $rc);
251

252
  return $rc;
253 254
}

255 256 257
/**
 * Retrieve a value from the cache.
 *
258 259 260 261
 * @param string $key
 *   The key with which the item was stored.
 * @param string $bin
 *   The bin in which the item was stored.
262
 *
263 264
 * @return mixed
 *   The item which was originally saved or FALSE
265
 */
266
function dmemcache_get($key, $bin = 'cache', $mc = NULL) {
267 268
  $collect_stats = dmemcache_stats_init();

269
  $result = FALSE;
270

271
  $full_key = dmemcache_key($key, $bin);
272 273 274 275 276
  if ($mc || $mc = dmemcache_object($bin)) {
    $track_errors = ini_set('track_errors', '1');
    $php_errormsg = '';

    $result = @$mc->get($full_key);
277 278 279 280
    // This is a multi-part value.
    if (is_object($result) && !empty($result->multi_part_data)) {
      $result = _dmemcache_get_pieces($result->data, $result->cid, $bin, $mc);
    }
281 282 283 284

    if (!empty($php_errormsg)) {
      register_shutdown_function('watchdog', 'memcache', 'Exception caught in dmemcache_get: !msg', array('!msg' => $php_errormsg), WATCHDOG_WARNING);
      $php_errormsg = '';
285
    }
286
    ini_set('track_errors', $track_errors);
287
  }
288

289 290 291 292
  if ($collect_stats) {
    dmemcache_stats_write('get', $bin, array($full_key => (bool) $result));
  }

293
  _dmemcache_write_debug('get', $bin, $full_key, (bool) $result);
294

295
  return $result;
296 297
}

298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
/**
 * Retrieve a value from the cache.
 *
 * @param $item
 *   The placeholder cache item from _dmemcache_set_pieces().
 * @param $key
 *   The key with which the item was stored.
 * @param string $bin
 *   (optional) The bin in which the item was stored.
 * @param object $mc
 *   (optional) The memcache object. Normally this value is
 *   determined automatically based on the bin the object is being stored to.
 *
 * @return object|bool
 *   The item which was originally saved or FALSE.
 */
function _dmemcache_get_pieces($item, $key, $bin = 'cache', $mc = NULL) {
  // Create a list of keys for the pieces of data.
  for ($id = 0; $id < $item->piece_count; $id++) {
    $keys[] = _dmemcache_key_piece($key, $id);
  }

320
  // Retrieve all the pieces of data and append them together.
321 322 323
  $pieces = dmemcache_get_multi($keys, $bin, $mc);
  $data = '';
  foreach ($pieces as $piece) {
324 325 326 327 328 329
    // The piece may be NULL if it didn't exist in memcache. If so,
    // we have to just return false for the entire set because we won't
    // be able to reconstruct the original data without all the pieces.
    if (!$piece) {
      return FALSE;
    }
330 331 332 333 334
    $data .= $piece->data;
  }
  unset($pieces);

  // If necessary unserialize the item.
335 336 337 338
  if (empty($item->serialized)) {
    return $data;
  }
  else {
339
    $unserialize_function = dmemcache_unserialize();
340
    return $unserialize_function($data);
341
  }
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
}

/**
 * Generates a key name for a multi-part data piece based on the sequence ID.
 *
 * @param int $id
 *   The sequence ID of the data piece.
 * @param int $key
 *   The original CID of the cache item.
 *
 * @return string
 */
function _dmemcache_key_piece($key, $id) {
  return dmemcache_key('_multi'. (string)$id . "-$key");
}

358 359 360
/**
 * Retrieve multiple values from the cache.
 *
361 362 363 364
 * @param array $keys
 *   The keys with which the items were stored.
 * @param string $bin
 *   The bin in which the item was stored.
365
 *
366
 * @return mixed
367 368
 *   An array keyed by $keys with the items requested or
 *   NULL values if the data was not present.
369 370
 */
function dmemcache_get_multi($keys, $bin = 'cache', $mc = NULL) {
371 372 373
  $collect_stats = dmemcache_stats_init();
  $multi_stats = array();

374
  $full_keys = array();
375

376 377
  foreach ($keys as $key => $cid) {
    $full_key = dmemcache_key($cid, $bin);
378
    $full_keys[$cid] = $full_key;
379 380 381 382

    if ($collect_stats) {
      $multi_stats[$full_key] = FALSE;
    }
383
  }
384

385 386
  $results = array();
  if ($mc || ($mc = dmemcache_object($bin))) {
387
    if ($mc instanceof Memcached) {
388 389 390 391 392 393 394 395
      if (PHP_MAJOR_VERSION >= 7) {
        // See https://www.drupal.org/node/2728427
        $results = $mc->getMulti($full_keys, Memcached::GET_PRESERVE_ORDER);
      }
      else {
        $cas_tokens = NULL;
        $results = $mc->getMulti($full_keys, $cas_tokens, Memcached::GET_PRESERVE_ORDER);
      }
396
    }
397
    elseif ($mc instanceof Memcache) {
398 399 400 401 402 403 404 405 406 407
      $track_errors = ini_set('track_errors', '1');
      $php_errormsg = '';

      $results = @$mc->get($full_keys);

      if (!empty($php_errormsg)) {
        register_shutdown_function('watchdog', 'memcache', 'Exception caught in dmemcache_get_multi: !msg', array('!msg' => $php_errormsg), WATCHDOG_WARNING);
        $php_errormsg = '';
      }
      ini_set('track_errors', $track_errors);
408 409 410 411 412 413

      // Order is not guaranteed, map responses to order of requests.
      if (is_array($results)) {
        $keys = array_fill_keys($full_keys, NULL);
        $results = array_merge($keys, $results);
      }
414 415
    }
  }
416

417 418 419
  // If $results is FALSE, convert it to an empty array.
  if (!$results) {
    $results = array();
420 421
    $keys = array_fill_keys($full_keys, NULL);
    $results = array_merge($keys, $results);
422
    _dmemcache_write_debug('getMulti', $bin, implode(',', $full_keys), FALSE);
423
  }
424

425 426 427 428 429 430
  if ($collect_stats) {
    foreach ($multi_stats as $key => $value) {
      $multi_stats[$key] = isset($results[$key]) ? TRUE : FALSE;
    }
  }

431 432
  // Convert the full keys back to the cid.
  $cid_results = array();
433 434
  $cid_lookup = array_flip($full_keys);
  foreach ($results as $key => $value) {
435 436 437 438
    // This is a multi-part value.
    if (is_object($value) && !empty($value->multi_part_data)) {
      $value = _dmemcache_get_pieces($value->data, $value->cid, $bin, $mc);
    }
439
    $cid_results[$cid_lookup[$key]] = $value;
440
    _dmemcache_write_debug('getMulti', $bin, $key, TRUE);
441
  }
442 443 444 445 446

  if ($collect_stats) {
    dmemcache_stats_write('getMulti', $bin, $multi_stats);
  }

447
  return $cid_results;
448 449 450 451 452
}

/**
 * Deletes an item from the cache.
 *
453 454 455 456
 * @param string $key
 *   The key with which the item was stored.
 * @param string $bin
 *   The bin in which the item was stored.
457
 *
458 459
 * @return bool
 *   Returns TRUE on success or FALSE on failure.
460
 */
461
function dmemcache_delete($key, $bin = 'cache', $mc = NULL) {
462 463
  $collect_stats = dmemcache_stats_init();

464
  $full_keys = dmemcache_key($key, $bin, TRUE);
465 466

  $rc = FALSE;
467
  if ($mc || ($mc = dmemcache_object($bin))) {
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
    foreach ($full_keys as $fk) {
      $rc = $mc->delete($fk, 0);

      if ($rc) {
        // If the delete succeeded, we now check to see if this item has
        //  multiple pieces also needing to be cleaned up. If the delete failed,
        // we assume these keys have already expired or been deleted (memcache
        // will auto-expire eventually if we're wrong).
        if ($piece_cache = dmemcache_piece_cache_get($fk)) {
          // First, remove from the piece_cache so we don't try and delete it
          // again in another thread, then delete the actual cache data pieces.
          dmemcache_piece_cache_set($fk, NULL);
          $next_id = 0;
          do {
            if ($inner_rc) {
              _dmemcache_write_debug("delete", $bin, $full_key, $inner_rc);
            }
            // Generate the cid of the next data piece.
            $piece_key = _dmemcache_key_piece($key, $next_id);
            $full_key = dmemcache_key($piece_key, $bin);
            $next_id++;

            // Keep deleting pieces until the operation fails. We accept that
            // this could lead to orphaned pieces as memcache will auto-expire
            // them eventually.
          } while ($inner_rc = $mc->delete($full_key, 0));
          _dmemcache_write_debug("delete", $bin, $full_key, $inner_rc);

          // Perform garbage collection for keys memcache has auto-expired. If
          // we don't do this, this variable could grow over enough time as a
          // slow memory leak.
          // @todo: Consider moving this to hook_cron() and requiring people to
          // enable the memcache module.
          timer_start('memcache_gc_piece_cache');
          $gc_counter = 0;
          $piece_cache = &drupal_static('dmemcache_piece_cache', array());
          foreach ($piece_cache as $cid => $expires) {
            if (REQUEST_TIME > $expires) {
              $gc_counter++;
              dmemcache_piece_cache_set($cid, NULL);
            }
          }
          if ($gc_counter) {
            register_shutdown_function('watchdog', 'memcache', 'Spent !time ms in garbage collection cleaning !count stale keys from the dmemcache_piece_cache.', array('!time' => timer_read('memcache_gc_piece_cache'), '!count' => $gc_counter), WATCHDOG_WARNING);
512 513 514
          }
        }
      }
515 516 517 518
      if ($collect_stats) {
        dmemcache_stats_write('delete', $bin, array($fk => $rc));
      }
      _dmemcache_write_debug('delete', $bin, $fk, $rc);
519
    }
520
  }
521 522

  return $rc;
523 524 525
}

/**
526 527 528 529 530
 * Flush all stored items.
 *
 * 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.
531
 *
532 533 534
 * @param string $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.
535
 *
536 537
 * @return bool
 *   Returns TRUE on success or FALSE on failure.
538
 */
539
function dmemcache_flush($bin = 'cache', $mc = NULL) {
540 541 542
  $collect_stats = dmemcache_stats_init();

  $rc = FALSE;
543
  if ($mc || ($mc = dmemcache_object($bin))) {
544
    $rc = $mc->flush();
545 546 547 548
  }

  if ($collect_stats) {
    dmemcache_stats_write('flush', $bin, array('' => $rc));
549
  }
550

551
  _dmemcache_write_debug('flush', $bin, $full_key, $rc);
552

553
  return $rc;
554 555
}

556 557 558 559 560 561 562 563 564 565
/**
 * Retrieves statistics recorded during memcache operations.
 *
 * @param string $stats_bin
 *   The bin to retrieve statistics for.
 * @param string $stats_type
 *   The type of statistics to retrieve when using the Memcache extension.
 * @param bool $aggregate
 *   Whether to aggregate statistics.
 */
566 567 568 569
function dmemcache_stats($stats_bin = 'cache', $stats_type = 'default', $aggregate = FALSE) {
  $memcache_bins = variable_get('memcache_bins', array('cache' => 'default'));
  // The stats_type can be over-loaded with an integer slab id, if doing a
  // cachedump.  We know we're doing a cachedump if $slab is non-zero.
570
  $slab = (int) $stats_type;
571
  $stats = array();
572 573 574 575 576 577 578 579 580 581 582

  foreach ($memcache_bins as $bin => $target) {
    if ($stats_bin == $bin) {
      if ($mc = dmemcache_object($bin)) {
        if ($mc instanceof Memcached) {
          $stats[$bin] = $mc->getStats();
        }
        // 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}. If $stats_type is 'default', then no parameter should be
        // passed to the Memcache memcache_get_extended_stats() function.
583
        elseif ($mc instanceof Memcache) {
584
          if ($stats_type == 'default' || $stats_type == '') {
585 586 587 588 589 590 591 592 593 594 595
            $rc = $mc->getExtendedStats();
            if (is_array($rc)) {
              foreach ($rc as $server => $data) {
                if (empty($data)) {
                  unset($rc[$server]);
                }
              }
              if (!empty($rc)) {
                $stats[$bin] = $rc;
              }
            }
596 597 598
          }
          // If $slab isn't zero, then we are dumping the contents of a
          // specific cache slab.
599
          elseif (!empty($slab)) {
600 601 602 603 604 605 606
            $stats[$bin] = $mc->getStats('cachedump', $slab);
          }
          else {
            $stats[$bin] = $mc->getExtendedStats($stats_type);
          }
        }
      }
607
    }
608 609 610 611
  }
  // Optionally calculate a sum-total for all servers in the current bin.
  if ($aggregate) {
    // Some variables don't logically aggregate.
612 613 614 615 616 617 618 619 620
    $no_aggregate = array(
      'pid',
      'time',
      'version',
      'pointer_size',
      'accepting_conns',
      'listen_disabled_num',
    );
    foreach ($stats as $bin => $servers) {
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
      if (is_array($servers)) {
        foreach ($servers as $server) {
          if (is_array($server)) {
            foreach ($server as $key => $value) {
              if (!in_array($key, $no_aggregate)) {
                if (isset($stats[$bin]['total'][$key])) {
                  $stats[$bin]['total'][$key] += $value;
                }
                else {
                  $stats[$bin]['total'][$key] = $value;
                }
              }
            }
          }
        }
      }
637
    }
638
  }
639
  return $stats;
640 641 642
}

/**
643
 * Determine which memcache extension to use: memcache or memcached.
644
 *
645 646
 * By default prefer the 'Memcache' PHP extension, though the default can be
 * overridden by setting memcache_extension in settings.php.
647
 */
648 649 650
function dmemcache_extension() {
  static $extension = NULL;
  if ($extension === NULL) {
651 652
    // If an extension is specified in settings.php, use that when available.
    $preferred = variable_get('memcache_extension', NULL);
653
    if (isset($preferred) && class_exists($preferred, FALSE)) {
654
      $extension = ucfirst(strtolower($preferred));
655 656
    }
    // If no extension is set, default to Memcache.
657
    elseif (class_exists('Memcache', FALSE)) {
658 659
      $extension = 'Memcache';
    }
660
    elseif (class_exists('Memcached', FALSE)) {
661 662
      $extension = 'Memcached';
    }
663 664 665 666 667 668 669
    else {
      $extension = FALSE;
    }
  }
  return $extension;
}

670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
/**
 * Determine which serialize extension to use: serialize (none), igbinary,
 * or msgpack.
 *
 * By default we prefer the igbinary extension, then the msgpack extension,
 * then the core serialize functions. This can be overridden in settings.php.
 */
function dmemcache_serialize_extension() {
  static $extension = NULL;
  if ($extension === NULL) {
    $preferred = strtolower(variable_get('memcache_serialize', NULL));
    // Fastpath if we're forcing php's own serialize function.
    if ($preferred == 'serialize') {
      $extension = $preferred;
    }
    // Otherwise, find an available extension favoring configuration.
    else {
      $igbinary_available = extension_loaded('igbinary');
      $msgpack_available = extension_loaded('msgpack');
      if ($preferred == 'igbinary' && $igbinary_available) {
        $extension = $preferred;
      }
      elseif ($preferred == 'msgpack' && $msgpack_available) {
        $extension = $preferred;
      }
      else {
        // No (valid) serialize extension specified, try igbinary.
        if ($igbinary_available) {
          $extension = 'igbinary';
        }
        // Next try msgpack.
        else if ($msgpack_available) {
          $extension = 'msgpack';
        }
        // Finally fall back to core serialize.
        else {
          $extension = 'serialize';
        }
      }
    }
  }
  return $extension;
}

/**
 * Return proper serialize function.
 */
function dmemcache_serialize() {
  switch (dmemcache_serialize_extension()) {
    case 'igbinary':
      return 'igbinary_serialize';
    case 'msgpack':
      return 'msgpack_pack';
    default:
      return 'serialize';
  }
}

/**
 * Return proper unserialize function.
 */
function dmemcache_unserialize() {
  switch (dmemcache_serialize_extension()) {
    case 'igbinary':
      return 'igbinary_unserialize';
    case 'msgpack':
      return 'msgpack_unpack';
    default:
      return 'unserialize';
  }
}

742 743 744
/**
 * Return a new memcache instance.
 */
745
function dmemcache_instance($bin = 'cache') {
746 747 748
  static $error = FALSE;
  $extension = dmemcache_extension();
  if ($extension == 'Memcache') {
749
    return new Memcache();
750 751
  }
  elseif ($extension == 'Memcached') {
752 753 754 755 756 757
    if (variable_get('memcache_persistent', TRUE)) {
      $memcache = new Memcached($bin);
    }
    else {
      $memcache = new Memcached;
    }
758 759 760 761 762 763 764 765 766 767 768 769 770
    $default_opts = array(
      Memcached::OPT_COMPRESSION => FALSE,
      Memcached::OPT_DISTRIBUTION => Memcached::DISTRIBUTION_CONSISTENT,
    );
    foreach ($default_opts as $key => $value) {
      $memcache->setOption($key, $value);
    }
    // See README.txt for setting custom Memcache options when using the
    // memcached PECL extension.
    $memconf = variable_get('memcache_options', array());
    foreach ($memconf as $key => $value) {
      $memcache->setOption($key, $value);
    }
771
    if (($sasl_username = variable_get('memcache_sasl_username', '')) && ($sasl_password = variable_get('memcache_sasl_password', ''))) {
772 773
      $memcache->setSaslAuthData($sasl_username, $sasl_password);
    }
774 775 776 777 778 779 780 781 782 783 784 785 786 787
    return $memcache;
  }
  else {
    if (!$error) {
      register_shutdown_function('watchdog', 'memcache', 'You must enable the PHP <a href="http://php.net/manual/en/book.memcache.php">memcache</a> (recommended) or <a href="http://php.net/manual/en/book.memcached.php">memcached</a> extension to use memcache.inc.', array(), WATCHDOG_ERROR);
      $error = TRUE;
    }
  }
  return FALSE;
}

/**
 * Initiate a connection to memcache.
 *
788 789 790 791
 * @param object $memcache
 *   A memcache instance obtained through dmemcache_instance.
 * @param string $server
 *   A server string of the format "localhost:11211" or
792
 *   "unix:///path/to/socket".
793 794
 * @param integer $weight
 *   Weighted probability of talking to this server.
795
 *
796 797
 * @return bool
 *   TRUE or FALSE if connection was successful.
798
 */
799
function dmemcache_connect($memcache, $server, $weight) {
800
  static $memcache_persistent = NULL;
801

802 803
  $extension = dmemcache_extension();

804 805 806 807
  @list($host, $port) = explode(':', trim($server));
  if (empty($host)) {
    register_shutdown_function('watchdog', 'memcache', 'You have specified an invalid address of "!server" in settings.php. Please review README.txt for proper configuration.', array('!server' => $server, '!ip' => t('127.0.0.1:11211'), '!host' => t('localhost:11211'), '!socket' => t('unix:///path/to/socket')), WATCHDOG_WARNING);
  }
808

809 810 811 812
  if (!isset($memcache_persistent)) {
    $memcache_persistent = variable_get('memcache_persistent', TRUE);
  }

813
  $port_error = FALSE;
814 815 816 817 818 819 820
  if ($extension == 'Memcache') {
    // Support unix sockets of the format 'unix:///path/to/socket'.
    if ($host == 'unix') {
      // Use full protocol and path as expected by Memcache extension.
      $host = $server;
      $port = 0;
    }
821
    else if (!isset($port)) {
822
      $port_error = TRUE;
823 824
    }
  }
825
  elseif ($extension == 'Memcached') {
826 827 828 829 830 831
    // Support unix sockets of the format 'unix:///path/to/socket'.
    if ($host == 'unix') {
      // Strip 'unix://' as expected by Memcached extension.
      $host = substr($server, 7);
      $port = 0;
    }
832
    else if (!isset($port)) {
833
      $port_error = TRUE;
834
    }
835 836 837 838 839 840 841 842 843 844 845
  }

  if ($port_error) {
    register_shutdown_function('watchdog', 'memcache', 'You have specified an invalid address of "!server" in settings.php which does not include a port. Please review README.txt for proper configuration. You must specify both a server address and port such as "!ip" or "!host", or a unix socket such as "!socket".', array('!server' => $server, '!ip' => t('127.0.0.1:11211'), '!host' => t('localhost:11211'), '!socket' => t('unix:///path/to/socket')), WATCHDOG_WARNING);
  }

  if ($extension == 'Memcache') {
    $rc = $memcache->addServer($host, $port, $memcache_persistent, $weight);
  }
  elseif ($extension == 'Memcached') {
    $match = FALSE;
846 847 848 849 850 851 852 853 854
    if ($memcache_persistent) {
      $servers = $memcache->getServerList();
      foreach ($servers as $s) {
        if ($s['host'] == $host && $s['port'] == $port) {
          $match = TRUE;
          break;
        }
      }
    }
855
    if (!$match) {
856 857
      $rc = $memcache->addServer($host, $port);
    }
858 859 860
    else {
      $rc = TRUE;
    }
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
  }
  else {
    $rc = FALSE;
  }
  return $rc;
}

/**
 * Close the connection to the memcache instance.
 */
function dmemcache_close($memcache) {
  $extension = dmemcache_extension();
  if ($extension == 'Memcache' && $memcache instanceof Memcache) {
    $rc = @$memcache->close;
  }
876
  elseif ($extension == 'Memcached' && $memcache instanceof Memcached) {
877
    $rc = @$memcache->quit;
878
  }
879 880 881 882 883 884 885 886 887 888 889 890 891 892
  else {
    $rc = FALSE;
  }
  return $rc;
}

/**
 * Return a Memcache object for the specified bin.
 *
 * 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.
 *
893 894 895 896
 * @param string $bin
 *   The bin which is to be used.
 * @param bool $flush
 *   Defaults to FALSE. Rebuild the bin/server/cache mapping.
897
 *
898 899
 * @return mixed
 *   A Memcache object, or FALSE on failure.
900 901
 */
function dmemcache_object($bin = NULL, $flush = FALSE) {
902
  static $memcache_cache = array();
903 904 905
  static $memcache_servers = array();
  static $memcache_bins = array();
  static $failed_connections = array();
906 907

  if ($flush) {
908 909 910 911 912 913 914 915 916 917
    if (!empty($memcache_cache)) {
      foreach ($memcache_cache as $cluster) {
        if ($extension == 'Memcache' && $cluster instanceof Memcache) {
          $rc = @$cluster->close;
        }
        elseif ($extension == 'Memcached' && $cluster instanceof Memcached) {
          $rc = @$cluster->quit;
        }
        $memcache_cache = array();
      }
918 919 920
    }
  }

921 922
  $extension = dmemcache_extension();

923
  if (empty($memcache_cache) || empty($memcache_cache[$bin])) {
924
    if (empty($memcache_servers)) {
925
      // Load the variables from settings.php if set.
926
      $memcache_servers = variable_get('memcache_servers', array('127.0.0.1:11211' => 'default'));
927
      $memcache_bins = variable_get('memcache_bins', array('cache' => 'default'));
928 929
    }

930
    // If not manually set, default this cluster to 'default'.
931 932
    $cluster = empty($memcache_bins[$bin]) ? 'default' : $memcache_bins[$bin];

933 934
    // If not manually set, map this bin to 'cache' which maps to the 'default'
    // cluster.
935 936
    if (empty($memcache_bins[$bin]) && !empty($memcache_cache['cache'])) {
      $memcache_cache[$bin] = &$memcache_cache['cache'];
937 938
    }
    else {
939
      // Create a new memcache object for each cluster.
940
      $memcache = dmemcache_instance($bin);
941

942 943 944
      // Track whether or not we've opened any memcache connections.
      $connection = FALSE;
      // Link all the servers to this cluster.
945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
      foreach ($memcache_servers as $server => $b) {
        if ($c = dmemcache_object_cluster($b)) {
          if ($c['cluster'] == $cluster && !isset($failed_connections[$server])) {
            $rc = dmemcache_connect($memcache, $server, $c['weight'], $connection);
            if ($rc) {
              // We've made at least one connection.
              $connection = TRUE;
            }
            else {
              // Memcache connection failure. We can't log to watchdog directly
              // because we're in an early Drupal bootstrap phase where watchdog
              // is non-functional. Instead, register a shutdown handler so it
              // gets recorded at the end of the page load.
              register_shutdown_function('watchdog', 'memcache', 'Failed to connect to memcache server: !server', array('!server' => $server), WATCHDOG_ERROR);
              $failed_connections[$server] = FALSE;
            }
961
          }
962 963
        }
      }
964
      if ($connection) {
965
        // Map the current bin with the new Memcache object.
966
        $memcache_cache[$bin] = $memcache;
967 968 969 970 971 972

        // 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.
973
            $memcache_cache[$b] = &$memcache_cache[$bin];
974 975 976 977 978 979
          }
        }
      }
    }
  }

980
  return empty($memcache_cache[$bin]) ? FALSE : $memcache_cache[$bin];
981 982
}

983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
/**
 * Ensure that we're working with a proper cluster array.
 */
function dmemcache_object_cluster($cluster) {
  if (!is_array($cluster)) {
    // Set defaults.
    $cluster = array(
      'cluster' => $cluster,
      'weight' => 1,
    );
  }
  if (!isset($cluster['cluster']) || !is_string($cluster['cluster'])) {
    // Cluster is required, complain if it's missing or invalid.
    register_shutdown_function('watchdog', 'memcache', 'Ignoring invalid or missing cluster definition, review your memcache_servers configuration.', array(), WATCHDOG_ERROR);
    return FALSE;
  }
  if (!isset($cluster['weight']) || !is_int($cluster['weight']) || $cluster['weight'] < 1) {
    // Weight is optional.
    $cluster['weight'] = 1;
  }
  return $cluster;
}

1006 1007 1008 1009 1010 1011 1012
/**
 * Prefixes a key and ensures it is url safe.
 *
 * @param string $key
 *   The key to prefix and encode.
 * @param string $bin
 *   The cache bin which the key applies to.
1013 1014
 * @param string $multiple
 *   If TRUE will return all possible prefix variations.
1015
 *
1016 1017
 * @return string or array
 *   The prefixed and encoded key(s).
1018
 */
1019
function dmemcache_key($key, $bin = 'cache', $multiple = FALSE) {
1020
  $prefix = '';
1021 1022
  if ($prefixes = variable_get('memcache_key_prefix', '')) {
    if (is_array($prefixes)) {
1023 1024 1025 1026
      // If no custom prefix defined for bin, use 'default'.
      if (empty($prefixes[$bin])) {
        $bin = 'default';
      }
1027
      if (!empty($prefixes[$bin])) {
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
        // There can be multiple prefixes specified for each bin.
        if (is_array($prefixes[$bin])) {
          // Optionally return key with all prefixes.
          if ($multiple) {
            $prefix = array();
            foreach ($prefixes[$bin] as $pre) {
              $prefix[] = $pre . '-';
            }
          }
          // Otherwise just return a single prefixed key.
          else {
            $prefix = $prefixes[$bin][0] . '-';
          }
        }
1042 1043 1044 1045 1046
      }
    }
    else {
      $prefix = $prefixes . '-';
    }
1047
  }
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059

  if (!is_array($prefix)) {
    $prefix = array($prefix);
  }
  $full_keys = array();
  foreach ($prefix as $p) {
    // When simpletest is running, emulate the simpletest database prefix here
    // to avoid the child site setting cache entries in the parent site.
    if (isset($GLOBALS['drupal_test_info']['test_run_id'])) {
      $p .= $GLOBALS['drupal_test_info']['test_run_id'];
    }
    $full_keys[] = urlencode($p . $bin . '-' . $key);
1060 1061
  }

1062 1063 1064 1065 1066 1067 1068 1069
  // Memcache truncates keys longer than 250 characters[*]. This could lead to
  // cache collisions, so we hash keys that are longer than this while still
  // retaining as much of the key bin and name as possible to aid in debugging.
  // The hashing algorithm used is configurable, with sha1 selected by default
  // as it performs quickly with minimal collisions. You can enforce shorter
  // keys by setting memcache_key_max_length in settings.php.
  // [*]https://github.com/memcached/memcached/blob/master/doc/protocol.txt#L47
  $maxlen = variable_get('memcache_key_max_length', 250);
1070 1071 1072 1073 1074 1075

  foreach ($full_keys as $k => $full_key) {
    if (strlen($full_key) > $maxlen) {
      $full_keys[$k] = urlencode($prefix[$k] . $bin) . '-' . hash(variable_get('memcache_key_hash_algorithm', 'sha1'), $key);
      $full_keys[$k] .= '-' . substr(urlencode($key), 0, ($maxlen - 1) - strlen($full_keys[$k]) - 1);
    }
1076
  }
1077

1078 1079 1080 1081 1082 1083 1084 1085
  if ($multiple) {
    // An array of prefixed keys.
    return $full_keys;
  }
  else {
    // A single prefixed key.
    return array_shift($full_keys);
  }
1086
}
1087

1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
/**
 * Track active keys with multi-piece values, necessary for efficient cleanup.
 *
 * We can't use variable_get/set for tracking this information because if the
 * variables array grows >1M and has to be split into pieces we'd get stuck in
 * an infinite loop. Storing this information in memcache means it can be lost,
 * but in that case the pieces will still eventually be auto-expired by
 * memcache.
 *
 * @param string $cid
 *   The cid of the root multi-piece value.
 * @param integer $exp
 *   Timestamp when the cached item expires. If NULL, the $cid will be deleted.
 *
 * @return bool
 *   TRUE on succes, FALSE otherwise.
 */
function dmemcache_piece_cache_set($cid, $exp = NULL) {
  // Always refresh cached copy to minimize multi-thread race window.
  $piece_cache = &drupal_static('dmemcache_piece_cache', array());
  $piece_cache = dmemcache_get('__dmemcache_piece_cache');
1109 1110 1111
  if (!is_array($piece_cache)) {
    $piece_cache = array();
  }
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160

  if (isset($exp)) {
    if ($exp <= 0) {
      // If no expiration time is set, defaults to 30 days.
      $exp = REQUEST_TIME + 2592000;
    }
    $piece_cache[$cid] = $exp;
  }
  else {
    unset($piece_cache[$cid]);
  }

  return dmemcache_set('__dmemcache_piece_cache', $piece_cache);
}

/**
 * Determine if a key has multi-piece values.
 *
 *
 * @param string $cid
 *   The cid to check for multi-piece values.
 *
 * @return integer
 *   Expiration time if key has multi-piece values, otherwise FALSE.
 */
function dmemcache_piece_cache_get($name) {
  static $drupal_static_fast;
  if (!isset($drupal_static_fast)) {
    $drupal_static_fast['piece_cache'] = &drupal_static('dmemcache_piece_cache', FALSE);
  }
  $piece_cache = &$drupal_static_fast['piece_cache'];

  if (!is_array($piece_cache)) {
    $piece_cache = dmemcache_get('__dmemcache_piece_cache');
    // On a website with no over-sized cache pieces, initialize the variable so
    // we never load it more than once per page versus once per DELETE.
    if (!is_array($piece_cache)) {
      dmemcache_set('__dmemcache_piece_cache', array());
    }
  }

  if (isset($piece_cache[$name])) {
    // Return the expiration time of the multi-piece cache item.
    return $piece_cache[$name];
  }
  // Item doesn't have multiple pieces.
  return FALSE;
}

1161
/**
1162 1163
 * Collect statistics if enabled.
 *
1164 1165 1166
 * Optimized function to determine whether or not we should be collecting
 * statistics. Also starts a timer to track how long individual memcache
 * operations take.
1167
 *
1168 1169
 * @return bool
 *   TRUE or FALSE if statistics should be collected.
1170
 */
1171
function dmemcache_stats_init() {
1172
  static $drupal_static_fast;
1173

1174 1175 1176 1177 1178 1179 1180
  if (!isset($drupal_static_fast)) {
    $drupal_static_fast = &drupal_static(__FUNCTION__, array('variable_checked' => NULL, 'user_access_checked' => NULL));
  }
  $variable_checked = &$drupal_static_fast['variable_checked'];
  $user_access_checked  = &$drupal_static_fast['user_access_checked'];

  // Confirm DRUPAL_BOOTSTRAP_VARIABLES has been reached. We don't use
1181 1182 1183
  // drupal_get_bootstrap_phase() as it's buggy. We can use variable_get() here
  // because _drupal_bootstrap_variables() includes module.inc immediately
  // after it calls variable_initialize().
1184 1185 1186 1187
  if (!isset($variable_checked) && function_exists('module_list')) {
    $variable_checked = variable_get('show_memcache_statistics', FALSE);
  }
  // If statistics are enabled we need to check user access.
1188
  if (!empty($variable_checked) && !isset($user_access_checked) && !empty($GLOBALS['user']) && function_exists('user_access')) {
1189 1190 1191 1192 1193
    // Statistics are enabled and the $user object has been populated, so check
    // that the user has access to view them.
    $user_access_checked = user_access('access memcache statistics');
  }
  // Return whether or not statistics are enabled and the user can access them.
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
  if ((!isset($variable_checked) || $variable_checked) && (!isset($user_access_checked) || $user_access_checked)) {
    timer_start('dmemcache');
    return TRUE;
  }
  else {
    return FALSE;
  }
}

/**
 * Save memcache statistics to be displayed at end of page generation.
 *
1206 1207 1208 1209 1210 1211 1212
 * @param string $action
 *   The action being performed (get, set, etc...).
 * @param string $bin
 *   The memcache bin the action is being performed in.
 * @param array $keys
 *   Keyed array in the form (string)$cid => (bool)$success. The keys the
 *   action is being performed on, and whether or not it was a success.
1213 1214
 */
function dmemcache_stats_write($action, $bin, $keys) {
1215
  global $_dmemcache_stats;
1216 1217 1218 1219
  // Determine how much time elapsed to execute this action.
  $time = timer_read('dmemcache');
  // Build the 'all' and 'ops' arrays displayed by memcache_admin.module.
  foreach ($keys as $key => $success) {
1220 1221 1222 1223 1224 1225 1226
    $_dmemcache_stats['all'][] = array(
      number_format($time, 2),
      $action,
      $bin,
      $key,
      $success ? 'hit' : 'miss',
    );
1227 1228 1229 1230
    if (!isset($_dmemcache_stats['ops'][$action])) {
      $_dmemcache_stats['ops'][$action] = array($action, 0, 0, 0);
    }
    $_dmemcache_stats['ops'][$action][1] += $time;
1231 1232 1233 1234 1235 1236
    if ($success) {
      $_dmemcache_stats['ops'][$action][2]++;
    }
    else {
      $_dmemcache_stats['ops'][$action][3]++;
    }
1237 1238
  }
  // Reset the dmemcache timer for timing the next memcache operation.
1239
}
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251

/**
 * Write to a debug log when enabled.
 *
 * @param string $action
 *   The action being performed (get, set, etc...).
 * @param string $bin
 *   The memcache bin the action is being performed in.
 * @param array $rc
 *   The return code of the action performed.
 */
function