3 // +---------------------------------------------------------------------------+
4 // | memcached client, PHP |
5 // +---------------------------------------------------------------------------+
6 // | Copyright (c) 2003 Ryan T. Dean <rtdean@cytherianage.net> |
7 // | All rights reserved. |
9 // | Redistribution and use in source and binary forms, with or without |
10 // | modification, are permitted provided that the following conditions |
13 // | 1. Redistributions of source code must retain the above copyright |
14 // | notice, this list of conditions and the following disclaimer. |
15 // | 2. Redistributions in binary form must reproduce the above copyright |
16 // | notice, this list of conditions and the following disclaimer in the |
17 // | documentation and/or other materials provided with the distribution. |
19 // | THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR |
20 // | IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES |
21 // | OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. |
22 // | IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, |
23 // | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT |
24 // | NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
25 // | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
26 // | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
27 // | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF |
28 // | THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
29 // +---------------------------------------------------------------------------+
30 // | Author: Ryan T. Dean <rtdean@cytherianage.net> |
31 // | Heavily influenced by the Perl memcached client by Brad Fitzpatrick. |
32 // | Permission granted by Brad Fitzpatrick for relicense of ported Perl |
33 // | client logic under 2-clause BSD license. |
34 // +---------------------------------------------------------------------------+
40 * This is the PHP client for memcached - a distributed memory cache daemon.
41 * More information is available at http://www.danga.com/memcached/
45 * require_once 'memcached.php';
47 * $mc = new memcached(array(
48 * 'servers' => array('127.0.0.1:10000',
49 * array('192.0.0.1:10010', 2),
52 * 'compress_threshold' => 10240,
53 * 'persistant' => true));
55 * $mc->add('key', array('some', 'array'));
56 * $mc->replace('key', 'some random string');
57 * $val = $mc->get('key');
59 * @author Ryan T. Dean <rtdean@cytherianage.net>
60 * @package memcached-client
71 * Flag: indicates data is serialized
73 define("MEMCACHE_SERIALIZED", 1<<0);
76 * Flag: indicates data is compressed
78 define("MEMCACHE_COMPRESSED", 1<<1);
83 * Minimum savings to store data compressed
85 define("COMPRESSION_SAVINGS", 0.20);
89 // {{{ class memcached
91 * memcached client class implemented using (p)fsockopen()
93 * @author Ryan T. Dean <rtdean@cytherianage.net>
94 * @package memcached-client
113 * Cached Sockets that are connected
121 * Current debug status; 0 - none to 9 - profiling
129 * Dead hosts, assoc array, 'host'=>'unixtime when ok to check again'
137 * Is compression available?
145 * Do we want to use compression?
150 var $_compress_enable;
153 * At how many bytes should we compress?
158 var $_compress_threshold;
161 * Are we using persistant links?
169 * If only using one server; contains ip:port to connect to
177 * Array containing ip:port or array(ip:port, weight)
193 * Total # of bit buckets we have
201 * # of total servers we have
211 // {{{ public functions
215 * Memcache initializer
217 * @param array $args Associative array of settings
222 function memcached ($args)
224 $this->set_servers(@$args['servers']);
225 $this->_debug
= @$args['debug'];
226 $this->stats
= array();
227 $this->_compress_threshold
= @$args['compress_threshold'];
228 $this->_persistant
= array_key_exists('persistant', $args) ?
(@$args['persistant']) : false;
229 $this->_compress_enable
= true;
230 $this->_have_zlib
= function_exists("gzcompress");
232 $this->_cache_sock
= array();
233 $this->_host_dead
= array();
240 * Adds a key/value to the memcache server if one isn't already set with
243 * @param string $key Key to set with data
244 * @param mixed $val Value to store
245 * @param interger $exp (optional) Time to expire data at
250 function add ($key, $val, $exp = 0)
252 return $this->_set('add', $key, $val, $exp);
259 * Decriment a value stored on the memcache server
261 * @param string $key Key to decriment
262 * @param interger $amt (optional) Amount to decriment
264 * @return mixed FALSE on failure, value on success
267 function decr ($key, $amt=1)
269 return $this->_incrdecr('decr', $key, $amt);
276 * Deletes a key from the server, optionally after $time
278 * @param string $key Key to delete
279 * @param interger $time (optional) How long to wait before deleting
281 * @return boolean TRUE on success, FALSE on failure
284 function delete ($key, $time = 0)
289 $sock = $this->get_sock($key);
290 if (!is_resource($sock))
293 $key = is_array($key) ?
$key[1] : $key;
295 $this->stats
['delete']++
;
296 $cmd = "delete $key $time\r\n";
297 if(!fwrite($sock, $cmd, strlen($cmd)))
299 $this->_dead_sock($sock);
302 $res = trim(fgets($sock));
305 $this->_debugprint(sprintf("MemCache: delete %s (%s)\n", $key, $res));
307 if ($res == "DELETED")
313 // {{{ disconnect_all()
316 * Disconnects all connected sockets
320 function disconnect_all ()
322 foreach ($this->_cache_sock
as $sock)
325 $this->_cache_sock
= array();
329 // {{{ enable_compress()
332 * Enable / Disable compression
334 * @param boolean $enable TRUE to enable, FALSE to disable
338 function enable_compress ($enable)
340 $this->_compress_enable
= $enable;
344 // {{{ forget_dead_hosts()
347 * Forget about all of the dead hosts
351 function forget_dead_hosts ()
353 $this->_host_dead
= array();
360 * Retrieves the value associated with the key from the memcache server
362 * @param string $key Key to retrieve
372 $sock = $this->get_sock($key);
374 if (!is_resource($sock))
377 @$this->stats
['get']++
;
379 $cmd = "get $key\r\n";
380 if (!fwrite($sock, $cmd, strlen($cmd)))
382 $this->_dead_sock($sock);
387 $this->_load_items($sock, $val);
390 foreach ($val as $k => $v)
391 $this->_debugprint(sprintf("MemCache: sock %s got %s => %s\r\n", $sock, $k, $v));
400 * Get multiple keys from the server(s)
402 * @param array $keys Keys to retrieve
407 function get_multi ($keys)
412 $this->stats
['get_multi']++
;
414 foreach ($keys as $key)
416 $sock = $this->get_sock($key);
417 if (!is_resource($sock)) continue;
418 $key = is_array($key) ?
$key[1] : $key;
419 if (!isset($sock_keys[$sock]))
421 $sock_keys[$sock] = array();
424 $sock_keys[$sock][] = $key;
427 // Send out the requests
428 foreach ($socks as $sock)
431 foreach ($sock_keys[$sock] as $key)
437 if (fwrite($sock, $cmd, strlen($cmd)))
442 $this->_dead_sock($sock);
448 foreach ($gather as $sock)
450 $this->_load_items($sock, $val);
454 foreach ($val as $k => $v)
455 $this->_debugprint(sprintf("MemCache: got %s => %s\r\n", $k, $v));
464 * Increments $key (optionally) by $amt
466 * @param string $key Key to increment
467 * @param interger $amt (optional) amount to increment
469 * @return interger New key value?
472 function incr ($key, $amt=1)
474 return $this->_incrdecr('incr', $key, $amt);
481 * Overwrites an existing value for key; only works if key is already set
483 * @param string $key Key to set value as
484 * @param mixed $value Value to store
485 * @param interger $exp (optional) Experiation time
490 function replace ($key, $value, $exp=0)
492 return $this->_set('replace', $key, $value, $exp);
499 * Passes through $cmd to the memcache server connected by $sock; returns
500 * output as an array (null array if no output)
502 * NOTE: due to a possible bug in how PHP reads while using fgets(), each
503 * line may not be terminated by a \r\n. More specifically, my testing
504 * has shown that, on FreeBSD at least, each line is terminated only
505 * with a \n. This is with the PHP flag auto_detect_line_endings set
506 * to falase (the default).
508 * @param resource $sock Socket to send command on
509 * @param string $cmd Command to run
511 * @return array Output array
514 function run_command ($sock, $cmd)
516 if (!is_resource($sock))
519 if (!fwrite($sock, $cmd, strlen($cmd)))
526 if (preg_match('/^END/', $res))
528 if (strlen($res) == 0)
538 * Unconditionally sets a key to a given value in the memcache. Returns true
539 * if set successfully.
541 * @param string $key Key to set value as
542 * @param mixed $value Value to set
543 * @param interger $exp (optional) Experiation time
545 * @return boolean TRUE on success
548 function set ($key, $value, $exp=0)
550 return $this->_set('set', $key, $value, $exp);
554 // {{{ set_compress_threshold()
557 * Sets the compression threshold
559 * @param interger $thresh Threshold to compress if larger than
563 function set_compress_threshold ($thresh)
565 $this->_compress_threshold
= $thresh;
572 * Sets the debug flag
574 * @param boolean $dbg TRUE for debugging, FALSE otherwise
578 * @see memcahced::memcached
580 function set_debug ($dbg)
582 $this->_debug
= $dbg;
589 * Sets the server list to distribute key gets and puts between
591 * @param array $list Array of servers to connect to
595 * @see memcached::memcached()
597 function set_servers ($list)
599 $this->_servers
= $list;
600 $this->_active
= count($list);
601 $this->_buckets
= null;
602 $this->_bucketcount
= 0;
604 $this->_single_sock
= null;
605 if ($this->_active
== 1)
606 $this->_single_sock
= $this->_servers
[0];
611 // {{{ private methods
615 * Close the specified socket
617 * @param string $sock Socket to close
621 function _close_sock ($sock)
623 $host = array_search($sock, $this->_cache_sock
);
624 fclose($this->_cache_sock
[$host]);
625 unset($this->_cache_sock
[$host]);
629 // {{{ _connect_sock()
632 * Connects $sock to $host, timing out after $timeout
634 * @param interger $sock Socket to connect
635 * @param string $host Host:IP to connect to
636 * @param float $timeout (optional) Timeout value, defaults to 0.25s
641 function _connect_sock (&$sock, $host, $timeout = 0.25)
643 list ($ip, $port) = explode(":", $host);
644 if ($this->_persistant
== 1)
646 $sock = @pfsockopen
($ip, $port, $errno, $errstr, $timeout);
649 $sock = @fsockopen
($ip, $port, $errno, $errstr, $timeout);
661 * Marks a host as dead until 30-40 seconds in the future
663 * @param string $sock Socket to mark as dead
667 function _dead_sock ($sock)
669 $host = array_search($sock, $this->_cache_sock
);
670 list ($ip, $port) = explode(":", $host);
671 $this->_host_dead
[$ip] = time() +
30 +
intval(rand(0, 10));
672 $this->_host_dead
[$host] = $this->_host_dead
[$ip];
673 unset($this->_cache_sock
[$host]);
682 * @param string $key Key to retrieve value for;
684 * @return mixed resource on success, false on failure
687 function get_sock ($key)
692 if ($this->_single_sock
!== null)
693 return $this->sock_to_host($this->_single_sock
);
695 $hv = is_array($key) ?
intval($key[0]) : $this->_hashfunc($key);
697 if ($this->_buckets
=== null)
699 foreach ($this->_servers
as $v)
703 for ($i=0; $i<$v[1]; $i++
)
710 $this->_buckets
= $bu;
711 $this->_bucketcount
= count($bu);
714 $realkey = is_array($key) ?
$key[1] : $key;
715 for ($tries = 0; $tries<20; $tries++
)
717 $host = $this->_buckets
[$hv %
$this->_bucketcount
];
718 $sock = $this->sock_to_host($host);
719 if (is_resource($sock))
721 $hv +
= $this->_hashfunc($tries . $realkey);
731 * Creates a hash interger based on the $key
733 * @param string $key Key to hash
735 * @return interger Hash value
738 function _hashfunc ($key)
741 for ($i=0; $i<strlen($key); $i++
)
743 $hash = $hash*33 +
ord($key[$i]);
753 * Perform increment/decriment on $key
755 * @param string $cmd Command to perform
756 * @param string $key Key to perform it on
757 * @param interger $amt Amount to adjust
759 * @return interger New value of $key
762 function _incrdecr ($cmd, $key, $amt=1)
767 $sock = $this->get_sock($key);
768 if (!is_resource($sock))
771 $key = is_array($key) ?
$key[1] : $key;
772 $this->stats
[$cmd]++
;
773 if (!fwrite($sock, "$cmd $key $amt\r\n"))
774 return $this->_dead_sock($sock);
776 stream_set_timeout($sock, 1, 0);
777 $line = fgets($sock);
778 if (!preg_match('/^(\d+)/', $line, $match))
787 * Load items into $ret from $sock
789 * @param resource $sock Socket to read from
790 * @param array $ret Returned values
794 function _load_items ($sock, &$ret)
798 $decl = fgets($sock);
799 if ($decl == "END\r\n")
802 } elseif (preg_match('/^VALUE (\S+) (\d+) (\d+)\r\n$/', $decl, $match))
804 list($rkey, $flags, $len) = array($match[1], $match[2], $match[3]);
810 $data = fread($sock, $bneed);
816 @$ret[$rkey] .= $data;
819 if ($offset != $len+
2)
821 // Something is borked!
823 $this->_debugprint(sprintf("Something is borked! key %s expecting %d got %d length\n", $rkey, $len+
2, $offset));
826 $this->_close_sock($sock);
830 $ret[$rkey] = rtrim($ret[$rkey]);
832 if ($this->_have_zlib
&& $flags & MEMCACHE_COMPRESSED
)
833 $ret[$rkey] = gzuncompress($ret[$rkey]);
835 if ($flags & MEMCACHE_SERIALIZED
)
836 $ret[$rkey] = unserialize($ret[$rkey]);
840 $this->_debugprint("Error parsing memcached response\n");
850 * Performs the requested storage operation to the memcache server
852 * @param string $cmd Command to perform
853 * @param string $key Key to act on
854 * @param mixed $val What we need to store
855 * @param interger $exp When it should expire
860 function _set ($cmd, $key, $val, $exp)
865 $sock = $this->get_sock($key);
866 if (!is_resource($sock))
869 @$this->stats
[$cmd]++
;
873 if (!is_scalar($val))
875 $val = serialize($val);
876 $flags |
= MEMCACHE_SERIALIZED
;
878 $this->_debugprint(sprintf("client: serializing data as it is not scalar\n"));
883 if ($this->_have_zlib
&& $this->_compress_enable
&&
884 $this->_compress_threshold
&& $len >= $this->_compress_threshold
)
886 $c_val = gzcompress($val, 9);
887 $c_len = strlen($c_val);
889 if ($c_len < $len*(1 - COMPRESS_SAVINGS
))
892 $this->_debugprint(sprintf("client: compressing data; was %d bytes is now %d bytes\n", $len, $c_len));
895 $flags |
= MEMCACHE_COMPRESSED
;
898 if (!fwrite($sock, "$cmd $key $flags $exp $len\r\n$val\r\n"))
899 return $this->_dead_sock($sock);
901 $line = trim(fgets($sock));
905 if ($flags & MEMCACHE_COMPRESSED
)
906 $val = 'compressed data';
907 $this->_debugprint(sprintf("MemCache: %s %s => %s (%s)\n", $cmd, $key, $val, $line));
909 if ($line == "STORED")
915 // {{{ sock_to_host()
918 * Returns the socket for the host
920 * @param string $host Host:IP to get socket for
922 * @return mixed IO Stream or false
925 function sock_to_host ($host)
927 if (isset($this->_cache_sock
[$host]))
928 return $this->_cache_sock
[$host];
931 list ($ip, $port) = explode (":", $host);
932 if (isset($this->_host_dead
[$host]) && $this->_host_dead
[$host] > $now ||
933 isset($this->_host_dead
[$ip]) && $this->_host_dead
[$ip] > $now)
936 if (!$this->_connect_sock($sock, $host))
937 return $this->_dead_sock($host);
939 // Do not buffer writes
940 stream_set_write_buffer($sock, 0);
942 $this->_cache_sock
[$host] = $sock;
944 return $this->_cache_sock
[$host];
947 function _debugprint($str){