3 * Memcached client for PHP.
5 * +---------------------------------------------------------------------------+
6 * | memcached client, PHP |
7 * +---------------------------------------------------------------------------+
8 * | Copyright (c) 2003 Ryan T. Dean <rtdean@cytherianage.net> |
9 * | All rights reserved. |
11 * | Redistribution and use in source and binary forms, with or without |
12 * | modification, are permitted provided that the following conditions |
15 * | 1. Redistributions of source code must retain the above copyright |
16 * | notice, this list of conditions and the following disclaimer. |
17 * | 2. Redistributions in binary form must reproduce the above copyright |
18 * | notice, this list of conditions and the following disclaimer in the |
19 * | documentation and/or other materials provided with the distribution. |
21 * | THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR |
22 * | IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES |
23 * | OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. |
24 * | IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, |
25 * | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT |
26 * | NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
27 * | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
28 * | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
29 * | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF |
30 * | THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
31 * +---------------------------------------------------------------------------+
32 * | Author: Ryan T. Dean <rtdean@cytherianage.net> |
33 * | Heavily influenced by the Perl memcached client by Brad Fitzpatrick. |
34 * | Permission granted by Brad Fitzpatrick for relicense of ported Perl |
35 * | client logic under 2-clause BSD license. |
36 * +---------------------------------------------------------------------------+
43 * This is the PHP client for memcached - a distributed memory cache daemon.
44 * More information is available at http://www.danga.com/memcached/
48 * require_once 'memcached.php';
50 * $mc = new MWMemcached(array(
51 * 'servers' => array('127.0.0.1:10000',
52 * array('192.0.0.1:10010', 2),
55 * 'compress_threshold' => 10240,
56 * 'persistent' => true));
58 * $mc->add( 'key', array( 'some', 'array' ) );
59 * $mc->replace( 'key', 'some random string' );
60 * $val = $mc->get( 'key' );
62 * @author Ryan T. Dean <rtdean@cytherianage.net>
69 // {{{ class MWMemcached
71 * memcached client class implemented using (p)fsockopen()
73 * @author Ryan T. Dean <rtdean@cytherianage.net>
84 * Flag: indicates data is serialized
89 * Flag: indicates data is compressed
96 * Minimum savings to store data compressed
98 const COMPRESSION_SAVINGS
= 0.20;
114 * Cached Sockets that are connected
122 * Current debug status; 0 - none to 9 - profiling
130 * Dead hosts, assoc array, 'host'=>'unixtime when ok to check again'
138 * Is compression available?
146 * Do we want to use compression?
151 var $_compress_enable;
154 * At how many bytes should we compress?
159 var $_compress_threshold;
162 * Are we using persistent links?
170 * If only using one server; contains ip:port to connect to
178 * Array containing ip:port or array(ip:port, weight)
194 * Total # of bit buckets we have
202 * # of total servers we have
210 * Stream timeout in seconds. Applies for example to fread()
215 var $_timeout_seconds;
218 * Stream timeout in microseconds
223 var $_timeout_microseconds;
226 * Connect timeout in seconds
228 var $_connect_timeout;
231 * Number of connection attempts for each server
233 var $_connect_attempts;
238 // {{{ public functions
242 * Memcache initializer
244 * @param array $args Associative array of settings
248 public function __construct( $args ) {
249 $this->set_servers( isset( $args['servers'] ) ?
$args['servers'] : array() );
250 $this->_debug
= isset( $args['debug'] ) ?
$args['debug'] : false;
251 $this->stats
= array();
252 $this->_compress_threshold
= isset( $args['compress_threshold'] ) ?
$args['compress_threshold'] : 0;
253 $this->_persistent
= isset( $args['persistent'] ) ?
$args['persistent'] : false;
254 $this->_compress_enable
= true;
255 $this->_have_zlib
= function_exists( 'gzcompress' );
257 $this->_cache_sock
= array();
258 $this->_host_dead
= array();
260 $this->_timeout_seconds
= 0;
261 $this->_timeout_microseconds
= isset( $args['timeout'] ) ?
$args['timeout'] : 500000;
263 $this->_connect_timeout
= isset( $args['connect_timeout'] ) ?
$args['connect_timeout'] : 0.1;
264 $this->_connect_attempts
= 2;
271 * Adds a key/value to the memcache server if one isn't already set with
274 * @param string $key key to set with data
275 * @param $val Mixed: value to store
276 * @param $exp Integer: (optional) Expiration time. This can be a number of seconds
277 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
278 * longer must be the timestamp of the time at which the mapping should expire. It
279 * is safe to use timestamps in all cases, regardless of expiration
280 * eg: strtotime("+3 hour")
284 public function add( $key, $val, $exp = 0 ) {
285 return $this->_set( 'add', $key, $val, $exp );
292 * Decrease a value stored on the memcache server
294 * @param string $key key to decrease
295 * @param $amt Integer: (optional) amount to decrease
297 * @return Mixed: FALSE on failure, value on success
299 public function decr( $key, $amt = 1 ) {
300 return $this->_incrdecr( 'decr', $key, $amt );
307 * Deletes a key from the server, optionally after $time
309 * @param string $key key to delete
310 * @param $time Integer: (optional) how long to wait before deleting
312 * @return Boolean: TRUE on success, FALSE on failure
314 public function delete( $key, $time = 0 ) {
315 if ( !$this->_active
) {
319 $sock = $this->get_sock( $key );
320 if ( !is_resource( $sock ) ) {
324 $key = is_array( $key ) ?
$key[1] : $key;
326 if ( isset( $this->stats
['delete'] ) ) {
327 $this->stats
['delete']++
;
329 $this->stats
['delete'] = 1;
331 $cmd = "delete $key $time\r\n";
332 if ( !$this->_fwrite( $sock, $cmd ) ) {
335 $res = $this->_fgets( $sock );
337 if ( $this->_debug
) {
338 $this->_debugprint( sprintf( "MemCache: delete %s (%s)\n", $key, $res ) );
341 if ( $res == "DELETED" ||
$res == "NOT_FOUND" ) {
350 * @param $timeout int
353 public function lock( $key, $timeout = 0 ) {
362 public function unlock( $key ) {
368 // {{{ disconnect_all()
371 * Disconnects all connected sockets
373 public function disconnect_all() {
374 foreach ( $this->_cache_sock
as $sock ) {
378 $this->_cache_sock
= array();
382 // {{{ enable_compress()
385 * Enable / Disable compression
387 * @param $enable Boolean: TRUE to enable, FALSE to disable
389 public function enable_compress( $enable ) {
390 $this->_compress_enable
= $enable;
394 // {{{ forget_dead_hosts()
397 * Forget about all of the dead hosts
399 public function forget_dead_hosts() {
400 $this->_host_dead
= array();
407 * Retrieves the value associated with the key from the memcache server
409 * @param array|string $key key to retrieve
410 * @param $casToken[optional] Float
414 public function get( $key, &$casToken = null ) {
415 wfProfileIn( __METHOD__
);
417 if ( $this->_debug
) {
418 $this->_debugprint( "get($key)\n" );
421 if ( !$this->_active
) {
422 wfProfileOut( __METHOD__
);
426 $sock = $this->get_sock( $key );
428 if ( !is_resource( $sock ) ) {
429 wfProfileOut( __METHOD__
);
433 $key = is_array( $key ) ?
$key[1] : $key;
434 if ( isset( $this->stats
['get'] ) ) {
435 $this->stats
['get']++
;
437 $this->stats
['get'] = 1;
440 $cmd = "gets $key\r\n";
441 if ( !$this->_fwrite( $sock, $cmd ) ) {
442 wfProfileOut( __METHOD__
);
447 $this->_load_items( $sock, $val, $casToken );
449 if ( $this->_debug
) {
450 foreach ( $val as $k => $v ) {
451 $this->_debugprint( sprintf( "MemCache: sock %s got %s\n", serialize( $sock ), $k ) );
456 if ( isset( $val[$key] ) ) {
459 wfProfileOut( __METHOD__
);
467 * Get multiple keys from the server(s)
469 * @param array $keys keys to retrieve
473 public function get_multi( $keys ) {
474 if ( !$this->_active
) {
478 if ( isset( $this->stats
['get_multi'] ) ) {
479 $this->stats
['get_multi']++
;
481 $this->stats
['get_multi'] = 1;
483 $sock_keys = array();
485 foreach ( $keys as $key ) {
486 $sock = $this->get_sock( $key );
487 if ( !is_resource( $sock ) ) {
490 $key = is_array( $key ) ?
$key[1] : $key;
491 if ( !isset( $sock_keys[$sock] ) ) {
492 $sock_keys[intval( $sock )] = array();
495 $sock_keys[intval( $sock )][] = $key;
499 // Send out the requests
500 foreach ( $socks as $sock ) {
502 foreach ( $sock_keys[intval( $sock )] as $key ) {
507 if ( $this->_fwrite( $sock, $cmd ) ) {
514 foreach ( $gather as $sock ) {
515 $this->_load_items( $sock, $val, $casToken );
518 if ( $this->_debug
) {
519 foreach ( $val as $k => $v ) {
520 $this->_debugprint( sprintf( "MemCache: got %s\n", $k ) );
531 * Increments $key (optionally) by $amt
533 * @param string $key key to increment
534 * @param $amt Integer: (optional) amount to increment
536 * @return Integer: null if the key does not exist yet (this does NOT
537 * create new mappings if the key does not exist). If the key does
538 * exist, this returns the new value for that key.
540 public function incr( $key, $amt = 1 ) {
541 return $this->_incrdecr( 'incr', $key, $amt );
548 * Overwrites an existing value for key; only works if key is already set
550 * @param string $key key to set value as
551 * @param $value Mixed: value to store
552 * @param $exp Integer: (optional) Expiration time. This can be a number of seconds
553 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
554 * longer must be the timestamp of the time at which the mapping should expire. It
555 * is safe to use timestamps in all cases, regardless of exipration
556 * eg: strtotime("+3 hour")
560 public function replace( $key, $value, $exp = 0 ) {
561 return $this->_set( 'replace', $key, $value, $exp );
568 * Passes through $cmd to the memcache server connected by $sock; returns
569 * output as an array (null array if no output)
571 * @param $sock Resource: socket to send command on
572 * @param string $cmd command to run
574 * @return Array: output array
576 public function run_command( $sock, $cmd ) {
577 if ( !is_resource( $sock ) ) {
581 if ( !$this->_fwrite( $sock, $cmd ) ) {
587 $res = $this->_fgets( $sock );
589 if ( preg_match( '/^END/', $res ) ) {
592 if ( strlen( $res ) == 0 ) {
603 * Unconditionally sets a key to a given value in the memcache. Returns true
604 * if set successfully.
606 * @param string $key key to set value as
607 * @param $value Mixed: value to set
608 * @param $exp Integer: (optional) Expiration time. This can be a number of seconds
609 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
610 * longer must be the timestamp of the time at which the mapping should expire. It
611 * is safe to use timestamps in all cases, regardless of exipration
612 * eg: strtotime("+3 hour")
614 * @return Boolean: TRUE on success
616 public function set( $key, $value, $exp = 0 ) {
617 return $this->_set( 'set', $key, $value, $exp );
624 * Sets a key to a given value in the memcache if the current value still corresponds
625 * to a known, given value. Returns true if set successfully.
627 * @param $casToken Float: current known value
628 * @param string $key key to set value as
629 * @param $value Mixed: value to set
630 * @param $exp Integer: (optional) Expiration time. This can be a number of seconds
631 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
632 * longer must be the timestamp of the time at which the mapping should expire. It
633 * is safe to use timestamps in all cases, regardless of exipration
634 * eg: strtotime("+3 hour")
636 * @return Boolean: TRUE on success
638 public function cas( $casToken, $key, $value, $exp = 0 ) {
639 return $this->_set( 'cas', $key, $value, $exp, $casToken );
643 // {{{ set_compress_threshold()
646 * Sets the compression threshold
648 * @param $thresh Integer: threshold to compress if larger than
650 public function set_compress_threshold( $thresh ) {
651 $this->_compress_threshold
= $thresh;
658 * Sets the debug flag
660 * @param $dbg Boolean: TRUE for debugging, FALSE otherwise
662 * @see MWMemcached::__construct
664 public function set_debug( $dbg ) {
665 $this->_debug
= $dbg;
672 * Sets the server list to distribute key gets and puts between
674 * @param array $list of servers to connect to
676 * @see MWMemcached::__construct()
678 public function set_servers( $list ) {
679 $this->_servers
= $list;
680 $this->_active
= count( $list );
681 $this->_buckets
= null;
682 $this->_bucketcount
= 0;
684 $this->_single_sock
= null;
685 if ( $this->_active
== 1 ) {
686 $this->_single_sock
= $this->_servers
[0];
691 * Sets the timeout for new connections
693 * @param $seconds Integer: number of seconds
694 * @param $microseconds Integer: number of microseconds
696 public function set_timeout( $seconds, $microseconds ) {
697 $this->_timeout_seconds
= $seconds;
698 $this->_timeout_microseconds
= $microseconds;
703 // {{{ private methods
707 * Close the specified socket
709 * @param string $sock socket to close
713 function _close_sock( $sock ) {
714 $host = array_search( $sock, $this->_cache_sock
);
715 fclose( $this->_cache_sock
[$host] );
716 unset( $this->_cache_sock
[$host] );
720 // {{{ _connect_sock()
723 * Connects $sock to $host, timing out after $timeout
725 * @param $sock Integer: socket to connect
726 * @param string $host Host:IP to connect to
731 function _connect_sock( &$sock, $host ) {
732 list( $ip, $port ) = explode( ':', $host );
734 $timeout = $this->_connect_timeout
;
735 $errno = $errstr = null;
736 for ( $i = 0; !$sock && $i < $this->_connect_attempts
; $i++
) {
737 wfSuppressWarnings();
738 if ( $this->_persistent
== 1 ) {
739 $sock = pfsockopen( $ip, $port, $errno, $errstr, $timeout );
741 $sock = fsockopen( $ip, $port, $errno, $errstr, $timeout );
746 $this->_error_log( "Error connecting to $host: $errstr\n" );
747 $this->_dead_host( $host );
751 // Initialise timeout
752 stream_set_timeout( $sock, $this->_timeout_seconds
, $this->_timeout_microseconds
);
754 // If the connection was persistent, flush the read buffer in case there
755 // was a previous incomplete request on this connection
756 if ( $this->_persistent
) {
757 $this->_flush_read_buffer( $sock );
766 * Marks a host as dead until 30-40 seconds in the future
768 * @param string $sock socket to mark as dead
772 function _dead_sock( $sock ) {
773 $host = array_search( $sock, $this->_cache_sock
);
774 $this->_dead_host( $host );
780 function _dead_host( $host ) {
781 $parts = explode( ':', $host );
783 $this->_host_dead
[$ip] = time() +
30 +
intval( rand( 0, 10 ) );
784 $this->_host_dead
[$host] = $this->_host_dead
[$ip];
785 unset( $this->_cache_sock
[$host] );
794 * @param string $key key to retrieve value for;
796 * @return Mixed: resource on success, false on failure
799 function get_sock( $key ) {
800 if ( !$this->_active
) {
804 if ( $this->_single_sock
!== null ) {
805 return $this->sock_to_host( $this->_single_sock
);
808 $hv = is_array( $key ) ?
intval( $key[0] ) : $this->_hashfunc( $key );
809 if ( $this->_buckets
=== null ) {
811 foreach ( $this->_servers
as $v ) {
812 if ( is_array( $v ) ) {
813 for ( $i = 0; $i < $v[1]; $i++
) {
820 $this->_buckets
= $bu;
821 $this->_bucketcount
= count( $bu );
824 $realkey = is_array( $key ) ?
$key[1] : $key;
825 for ( $tries = 0; $tries < 20; $tries++
) {
826 $host = $this->_buckets
[$hv %
$this->_bucketcount
];
827 $sock = $this->sock_to_host( $host );
828 if ( is_resource( $sock ) ) {
831 $hv = $this->_hashfunc( $hv . $realkey );
841 * Creates a hash integer based on the $key
843 * @param string $key key to hash
845 * @return Integer: hash value
848 function _hashfunc( $key ) {
849 # Hash function must be in [0,0x7ffffff]
850 # We take the first 31 bits of the MD5 hash, which unlike the hash
851 # function used in a previous version of this client, works
852 return hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
859 * Perform increment/decriment on $key
861 * @param string $cmd command to perform
862 * @param string|array $key key to perform it on
863 * @param $amt Integer amount to adjust
865 * @return Integer: new value of $key
868 function _incrdecr( $cmd, $key, $amt = 1 ) {
869 if ( !$this->_active
) {
873 $sock = $this->get_sock( $key );
874 if ( !is_resource( $sock ) ) {
878 $key = is_array( $key ) ?
$key[1] : $key;
879 if ( isset( $this->stats
[$cmd] ) ) {
880 $this->stats
[$cmd]++
;
882 $this->stats
[$cmd] = 1;
884 if ( !$this->_fwrite( $sock, "$cmd $key $amt\r\n" ) ) {
888 $line = $this->_fgets( $sock );
890 if ( !preg_match( '/^(\d+)/', $line, $match ) ) {
900 * Load items into $ret from $sock
902 * @param $sock Resource: socket to read from
903 * @param array $ret returned values
904 * @param $casToken[optional] Float
905 * @return boolean True for success, false for failure
909 function _load_items( $sock, &$ret, &$casToken = null ) {
913 $decl = $this->_fgets( $sock );
915 if ( $decl === false ) {
917 * If nothing can be read, something is wrong because we know exactly when
918 * to stop reading (right after "END") and we return right after that.
921 } elseif ( preg_match( '/^VALUE (\S+) (\d+) (\d+) (\d+)$/', $decl, $match ) ) {
923 * Read all data returned. This can be either one or multiple values.
924 * Save all that data (in an array) to be processed later: we'll first
925 * want to continue reading until "END" before doing anything else,
926 * to make sure that we don't leave our client in a state where it's
927 * output is not yet fully read.
933 $match[4], // casToken
934 $this->_fread( $sock, $match[3] +
2 ), // data
936 } elseif ( $decl == "END" ) {
937 if ( count( $results ) == 0 ) {
942 * All data has been read, time to process the data and build
943 * meaningful return values.
945 foreach ( $results as $vars ) {
946 list( $rkey, $flags, $len, $casToken, $data ) = $vars;
948 if ( $data === false ||
substr( $data, -2 ) !== "\r\n" ) {
949 $this->_handle_error( $sock,
950 'line ending missing from data block from $1' );
953 $data = substr( $data, 0, -2 );
956 if ( $this->_have_zlib
&& $flags & self
::COMPRESSED
) {
957 $ret[$rkey] = gzuncompress( $ret[$rkey] );
961 * This unserialize is the exact reason that we only want to
962 * process data after having read until "END" (instead of doing
963 * this right away): "unserialize" can trigger outside code:
964 * in the event that $ret[$rkey] is a serialized object,
965 * unserializing it will trigger __wakeup() if present. If that
966 * function attempted to read from memcached (while we did not
967 * yet read "END"), these 2 calls would collide.
969 if ( $flags & self
::SERIALIZED
) {
970 $ret[$rkey] = unserialize( $ret[$rkey] );
976 $this->_handle_error( $sock, 'Error parsing response from $1' );
986 * Performs the requested storage operation to the memcache server
988 * @param string $cmd command to perform
989 * @param string $key key to act on
990 * @param $val Mixed: what we need to store
991 * @param $exp Integer: (optional) Expiration time. This can be a number of seconds
992 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
993 * longer must be the timestamp of the time at which the mapping should expire. It
994 * is safe to use timestamps in all cases, regardless of exipration
995 * eg: strtotime("+3 hour")
996 * @param $casToken[optional] Float
1001 function _set( $cmd, $key, $val, $exp, $casToken = null ) {
1002 if ( !$this->_active
) {
1006 $sock = $this->get_sock( $key );
1007 if ( !is_resource( $sock ) ) {
1011 if ( isset( $this->stats
[$cmd] ) ) {
1012 $this->stats
[$cmd]++
;
1014 $this->stats
[$cmd] = 1;
1019 if ( !is_scalar( $val ) ) {
1020 $val = serialize( $val );
1021 $flags |
= self
::SERIALIZED
;
1022 if ( $this->_debug
) {
1023 $this->_debugprint( sprintf( "client: serializing data as it is not scalar\n" ) );
1027 $len = strlen( $val );
1029 if ( $this->_have_zlib
&& $this->_compress_enable
&&
1030 $this->_compress_threshold
&& $len >= $this->_compress_threshold
)
1032 $c_val = gzcompress( $val, 9 );
1033 $c_len = strlen( $c_val );
1035 if ( $c_len < $len * ( 1 - self
::COMPRESSION_SAVINGS
) ) {
1036 if ( $this->_debug
) {
1037 $this->_debugprint( sprintf( "client: compressing data; was %d bytes is now %d bytes\n", $len, $c_len ) );
1041 $flags |
= self
::COMPRESSED
;
1045 $command = "$cmd $key $flags $exp $len";
1047 $command .= " $casToken";
1050 if ( !$this->_fwrite( $sock, "$command\r\n$val\r\n" ) ) {
1054 $line = $this->_fgets( $sock );
1056 if ( $this->_debug
) {
1057 $this->_debugprint( sprintf( "%s %s (%s)\n", $cmd, $key, $line ) );
1059 if ( $line == "STORED" ) {
1066 // {{{ sock_to_host()
1069 * Returns the socket for the host
1071 * @param string $host Host:IP to get socket for
1073 * @return Mixed: IO Stream or false
1076 function sock_to_host( $host ) {
1077 if ( isset( $this->_cache_sock
[$host] ) ) {
1078 return $this->_cache_sock
[$host];
1083 list( $ip, /* $port */) = explode( ':', $host );
1084 if ( isset( $this->_host_dead
[$host] ) && $this->_host_dead
[$host] > $now ||
1085 isset( $this->_host_dead
[$ip] ) && $this->_host_dead
[$ip] > $now
1090 if ( !$this->_connect_sock( $sock, $host ) ) {
1094 // Do not buffer writes
1095 stream_set_write_buffer( $sock, 0 );
1097 $this->_cache_sock
[$host] = $sock;
1099 return $this->_cache_sock
[$host];
1103 * @param $text string
1105 function _debugprint( $text ) {
1106 wfDebugLog( 'memcached', $text );
1110 * @param $text string
1112 function _error_log( $text ) {
1113 wfDebugLog( 'memcached-serious', "Memcached error: $text" );
1117 * Write to a stream. If there is an error, mark the socket dead.
1119 * @param $sock The socket
1120 * @param $buf The string to write
1121 * @return bool True on success, false on failure
1123 function _fwrite( $sock, $buf ) {
1125 $bufSize = strlen( $buf );
1126 while ( $bytesWritten < $bufSize ) {
1127 $result = fwrite( $sock, $buf );
1128 $data = stream_get_meta_data( $sock );
1129 if ( $data['timed_out'] ) {
1130 $this->_handle_error( $sock, 'timeout writing to $1' );
1133 // Contrary to the documentation, fwrite() returns zero on error in PHP 5.3.
1134 if ( $result === false ||
$result === 0 ) {
1135 $this->_handle_error( $sock, 'error writing to $1' );
1138 $bytesWritten +
= $result;
1145 * Handle an I/O error. Mark the socket dead and log an error.
1147 function _handle_error( $sock, $msg ) {
1148 $peer = stream_socket_get_name( $sock, true /** remote **/ );
1149 if ( strval( $peer ) === '' ) {
1150 $peer = array_search( $sock, $this->_cache_sock
);
1151 if ( $peer === false ) {
1152 $peer = '[unknown host]';
1155 $msg = str_replace( '$1', $peer, $msg );
1156 $this->_error_log( "$msg\n" );
1157 $this->_dead_sock( $sock );
1161 * Read the specified number of bytes from a stream. If there is an error,
1162 * mark the socket dead.
1164 * @param $sock The socket
1165 * @param $len The number of bytes to read
1166 * @return The string on success, false on failure.
1168 function _fread( $sock, $len ) {
1170 while ( $len > 0 ) {
1171 $result = fread( $sock, $len );
1172 $data = stream_get_meta_data( $sock );
1173 if ( $data['timed_out'] ) {
1174 $this->_handle_error( $sock, 'timeout reading from $1' );
1177 if ( $result === false ) {
1178 $this->_handle_error( $sock, 'error reading buffer from $1' );
1181 if ( $result === '' ) {
1182 // This will happen if the remote end of the socket is shut down
1183 $this->_handle_error( $sock, 'unexpected end of file reading from $1' );
1186 $len -= strlen( $result );
1193 * Read a line from a stream. If there is an error, mark the socket dead.
1194 * The \r\n line ending is stripped from the response.
1196 * @param $sock The socket
1197 * @return The string on success, false on failure
1199 function _fgets( $sock ) {
1200 $result = fgets( $sock );
1201 // fgets() may return a partial line if there is a select timeout after
1202 // a successful recv(), so we have to check for a timeout even if we
1203 // got a string response.
1204 $data = stream_get_meta_data( $sock );
1205 if ( $data['timed_out'] ) {
1206 $this->_handle_error( $sock, 'timeout reading line from $1' );
1209 if ( $result === false ) {
1210 $this->_handle_error( $sock, 'error reading line from $1' );
1213 if ( substr( $result, -2 ) === "\r\n" ) {
1214 $result = substr( $result, 0, -2 );
1215 } elseif ( substr( $result, -1 ) === "\n" ) {
1216 $result = substr( $result, 0, -1 );
1218 $this->_handle_error( $sock, 'line ending missing in response from $1' );
1225 * Flush the read buffer of a stream
1226 * @param $f Resource
1228 function _flush_read_buffer( $f ) {
1229 if ( !is_resource( $f ) ) {
1235 $n = stream_select( $r, $w, $e, 0, 0 );
1236 while ( $n == 1 && !feof( $f ) ) {
1241 $n = stream_select( $r, $w, $e, 0, 0 );
1252 class MemCachedClientforWiki
extends MWMemcached
{