69use Psr\Log\LoggerInterface;
70use Psr\Log\NullLogger;
262 $this->_debug =
$args[
'debug'] ??
false;
263 $this->stats = array();
264 $this->_compress_threshold =
$args[
'compress_threshold'] ?? 0;
265 $this->_persistent =
$args[
'persistent'] ??
false;
266 $this->_compress_enable =
true;
267 $this->_have_zlib = function_exists(
'gzcompress' );
269 $this->_cache_sock = array();
270 $this->_host_dead = array();
272 $this->_timeout_seconds = 0;
273 $this->_timeout_microseconds =
$args[
'timeout'] ?? 500000;
275 $this->_connect_timeout =
$args[
'connect_timeout'] ?? 0.1;
276 $this->_connect_attempts = 2;
278 $this->_logger =
$args[
'logger'] ??
new NullLogger();
315 public function add( $key, $val, $exp = 0 ) {
316 return $this->
_set(
'add', $key, $val, $exp );
330 public function decr( $key, $amt = 1 ) {
331 return $this->
_incrdecr(
'decr', $key, $amt );
345 public function delete( $key, $time = 0 ) {
346 if ( !$this->_active ) {
355 $key = is_array( $key ) ? $key[1] : $key;
357 if ( isset( $this->stats[
'delete'] ) ) {
358 $this->stats[
'delete']++;
360 $this->stats[
'delete'] = 1;
362 $cmd =
"delete $key $time\r\n";
363 if ( !$this->
_fwrite( $sock, $cmd ) ) {
368 if ( $this->_debug ) {
369 $this->
_debugprint( sprintf(
"MemCache: delete %s (%s)", $key,
$res ) );
372 if (
$res ==
"DELETED" ||
$res ==
"NOT_FOUND" ) {
387 public function touch( $key, $time = 0 ) {
388 if ( !$this->_active ) {
397 $key = is_array( $key ) ? $key[1] : $key;
399 if ( isset( $this->stats[
'touch'] ) ) {
400 $this->stats[
'touch']++;
402 $this->stats[
'touch'] = 1;
404 $cmd =
"touch $key $time\r\n";
405 if ( !$this->
_fwrite( $sock, $cmd ) ) {
410 if ( $this->_debug ) {
411 $this->
_debugprint( sprintf(
"MemCache: touch %s (%s)", $key,
$res ) );
414 if (
$res ==
"TOUCHED" ) {
428 foreach ( $this->_cache_sock as $sock ) {
432 $this->_cache_sock = array();
444 $this->_compress_enable = $enable;
454 $this->_host_dead = array();
468 public function get( $key, &$casToken = null ) {
469 $getToken = ( func_num_args() >= 2 );
471 if ( $this->_debug ) {
475 if ( !is_array( $key ) && strval( $key ) ===
'' ) {
476 $this->
_debugprint(
"Skipping key which equals to an empty string" );
480 if ( !$this->_active ) {
490 $key = is_array( $key ) ? $key[1] : $key;
491 if ( isset( $this->stats[
'get'] ) ) {
492 $this->stats[
'get']++;
494 $this->stats[
'get'] = 1;
497 $cmd = $getToken ?
"gets" :
"get";
499 if ( !$this->
_fwrite( $sock, $cmd ) ) {
506 if ( $this->_debug ) {
507 foreach ( $val as $k => $v ) {
509 sprintf(
"MemCache: sock %s got %s", $this->
serialize( $sock ), $k ) );
514 if ( isset( $val[$key] ) ) {
531 if ( !$this->_active ) {
535 if ( isset( $this->stats[
'get_multi'] ) ) {
536 $this->stats[
'get_multi']++;
538 $this->stats[
'get_multi'] = 1;
540 $sock_keys = array();
542 foreach (
$keys as $key ) {
547 $key = is_array( $key ) ? $key[1] : $key;
548 $sockValue = intval( $sock );
550 if ( !isset( $sock_keys[$sockValue] ) ) {
551 $sock_keys[$sockValue] = array();
554 $sock_keys[$sockValue][] = $key;
559 foreach ( $socks as $sock ) {
561 foreach ( $sock_keys[intval( $sock )] as $key ) {
566 if ( $this->
_fwrite( $sock, $cmd ) ) {
573 foreach ( $gather as $sock ) {
577 if ( $this->_debug ) {
578 foreach ( $val as $k => $v ) {
579 $this->
_debugprint( sprintf(
"MemCache: got %s", $k ) );
599 public function incr( $key, $amt = 1 ) {
600 return $this->
_incrdecr(
'incr', $key, $amt );
619 public function replace( $key, $value, $exp = 0 ) {
620 return $this->
_set(
'replace', $key, $value, $exp );
640 if ( !$this->
_fwrite( $sock, $cmd ) ) {
648 if ( preg_match(
'/^END/',
$res ) ) {
651 if ( strlen(
$res ) == 0 ) {
675 public function set( $key, $value, $exp = 0 ) {
676 return $this->
_set(
'set', $key, $value, $exp );
697 public function cas( $casToken, $key, $value, $exp = 0 ) {
698 return $this->
_set(
'cas', $key, $value, $exp, $casToken );
710 $this->_compress_threshold = $thresh;
723 $this->_debug = $dbg;
736 $this->_servers = $list;
737 $this->_active = count( $list );
738 $this->_buckets =
null;
739 $this->_bucketcount = 0;
741 $this->_single_sock =
null;
742 if ( $this->_active == 1 ) {
743 $this->_single_sock = $this->_servers[0];
754 $this->_timeout_seconds = $seconds;
755 $this->_timeout_microseconds = $microseconds;
771 $host = array_search( $sock, $this->_cache_sock );
772 fclose( $this->_cache_sock[$host] );
773 unset( $this->_cache_sock[$host] );
790 $hostAndPort = IPUtils::splitHostAndPort( $host );
791 if ( $hostAndPort ) {
792 $ip = $hostAndPort[0];
793 if ( $hostAndPort[1] ) {
794 $port = $hostAndPort[1];
801 $errno = $errstr =
null;
803 Wikimedia\suppressWarnings();
804 if ( $this->_persistent == 1 ) {
805 $sock = pfsockopen( $ip, $port, $errno, $errstr, $timeout );
807 $sock = fsockopen( $ip, $port, $errno, $errstr, $timeout );
809 Wikimedia\restoreWarnings();
812 $this->
_error_log(
"Error connecting to $host: $errstr" );
818 stream_set_timeout( $sock, $this->_timeout_seconds, $this->_timeout_microseconds );
822 if ( $this->_persistent ) {
839 $host = array_search( $sock, $this->_cache_sock );
847 $hostAndPort = IPUtils::splitHostAndPort( $host );
848 if ( $hostAndPort ) {
849 $ip = $hostAndPort[0];
853 $this->_host_dead[$ip] = time() + 30 + intval( rand( 0, 10 ) );
854 $this->_host_dead[$host] = $this->_host_dead[$ip];
855 unset( $this->_cache_sock[$host] );
870 if ( !$this->_active ) {
874 if ( $this->_single_sock !==
null ) {
878 $hv = is_array( $key ) ? intval( $key[0] ) : $this->
_hashfunc( $key );
879 if ( $this->_buckets ===
null ) {
881 foreach ( $this->_servers as $v ) {
882 if ( is_array( $v ) ) {
883 for ( $i = 0; $i < $v[1]; $i++ ) {
890 $this->_buckets = $bu;
891 $this->_bucketcount = count( $bu );
894 $realkey = is_array( $key ) ? $key[1] : $key;
895 for ( $tries = 0; $tries < 20; $tries++ ) {
901 $hv = $this->
_hashfunc( $hv . $realkey );
919 # Hash function must be in [0,0x7ffffff]
920 # We take the first 31 bits of the MD5 hash, which unlike the hash
921 # function used in a previous version of this client, works
922 return hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
939 if ( !$this->_active ) {
948 $key = is_array( $key ) ? $key[1] : $key;
949 if ( isset( $this->stats[$cmd] ) ) {
950 $this->stats[$cmd]++;
952 $this->stats[$cmd] = 1;
954 if ( !$this->
_fwrite( $sock,
"$cmd $key $amt\r\n" ) ) {
960 if ( !preg_match(
'/^(\d+)/',
$line, $match ) ) {
983 $decl = $this->
_fgets( $sock );
985 if ( $decl ===
false ) {
991 } elseif ( preg_match(
'/^VALUE (\S+) (\d+) (\d+)(?: (\d+))?$/', $decl, $match ) ) {
1004 $this->
_fread( $sock, $match[3] + 2 ),
1006 } elseif ( $decl ==
"END" ) {
1007 if ( count( $results ) == 0 ) {
1015 foreach ( $results as [ $rkey, $flags, , $casToken, $data ] ) {
1016 if ( $data ===
false || substr( $data, -2 ) !==
"\r\n" ) {
1018 'line ending missing from data block from $1' );
1021 $data = substr( $data, 0, -2 );
1022 $ret[$rkey] = $data;
1024 if ( $this->_have_zlib && $flags & self::COMPRESSED ) {
1025 $ret[$rkey] = gzuncompress( $ret[$rkey] );
1037 if ( $flags & self::SERIALIZED ) {
1039 } elseif ( $flags & self::INTVAL ) {
1040 $ret[$rkey] = intval( $ret[$rkey] );
1046 $this->
_handle_error( $sock,
'Error parsing response from $1' );
1071 function _set( $cmd, $key, $val, $exp, $casToken =
null ) {
1072 if ( !$this->_active ) {
1081 if ( isset( $this->stats[$cmd] ) ) {
1082 $this->stats[$cmd]++;
1084 $this->stats[$cmd] = 1;
1089 if ( is_int( $val ) ) {
1091 } elseif ( !is_scalar( $val ) ) {
1094 if ( $this->_debug ) {
1095 $this->
_debugprint( sprintf(
"client: serializing data as it is not scalar" ) );
1099 $len = strlen( $val );
1101 if ( $this->_have_zlib && $this->_compress_enable
1102 && $this->_compress_threshold && $len >= $this->_compress_threshold
1104 $c_val = gzcompress( $val, 9 );
1105 $c_len = strlen( $c_val );
1107 if ( $c_len < $len * ( 1 - self::COMPRESSION_SAVINGS ) ) {
1108 if ( $this->_debug ) {
1109 $this->
_debugprint( sprintf(
"client: compressing data; was %d bytes is now %d bytes", $len, $c_len ) );
1117 $command =
"$cmd $key $flags $exp $len";
1122 if ( !$this->
_fwrite( $sock,
"$command\r\n$val\r\n" ) ) {
1128 if ( $this->_debug ) {
1131 if (
$line ===
"STORED" ) {
1133 } elseif (
$line ===
"NOT_STORED" && $cmd ===
"set" ) {
1153 if ( isset( $this->_cache_sock[$host] ) ) {
1154 return $this->_cache_sock[$host];
1159 $hostAndPort = IPUtils::splitHostAndPort( $host );
1160 if ( $hostAndPort ) {
1161 $ip = $hostAndPort[0];
1165 if ( isset( $this->_host_dead[$host] ) && $this->_host_dead[$host] > $now ||
1166 isset( $this->_host_dead[$ip] ) && $this->_host_dead[$ip] > $now
1176 stream_set_write_buffer( $sock, 0 );
1178 $this->_cache_sock[$host] = $sock;
1180 return $this->_cache_sock[$host];
1187 $this->_logger->debug( $text );
1194 $this->_logger->error(
"Memcached error: $text" );
1206 $bufSize = strlen( $buf );
1207 while ( $bytesWritten < $bufSize ) {
1208 $result = fwrite( $sock, $buf );
1209 $data = stream_get_meta_data( $sock );
1210 if ( $data[
'timed_out'] ) {
1215 if ( $result ===
false || $result === 0 ) {
1219 $bytesWritten += $result;
1232 $peer = stream_socket_get_name( $sock,
true );
1233 if ( strval( $peer ) ===
'' ) {
1234 $peer = array_search( $sock, $this->_cache_sock );
1235 if ( $peer ===
false ) {
1236 $peer =
'[unknown host]';
1239 $msg = str_replace(
'$1', $peer, $msg );
1254 while ( $len > 0 ) {
1255 $result = fread( $sock, $len );
1256 $data = stream_get_meta_data( $sock );
1257 if ( $data[
'timed_out'] ) {
1261 if ( $result ===
false ) {
1262 $this->
_handle_error( $sock,
'error reading buffer from $1' );
1265 if ( $result ===
'' ) {
1267 $this->
_handle_error( $sock,
'unexpected end of file reading from $1' );
1270 $len -= strlen( $result );
1284 $result = fgets( $sock );
1288 $data = stream_get_meta_data( $sock );
1289 if ( $data[
'timed_out'] ) {
1290 $this->
_handle_error( $sock,
'timeout reading line from $1' );
1293 if ( $result ===
false ) {
1294 $this->
_handle_error( $sock,
'error reading line from $1' );
1297 if ( substr( $result, -2 ) ===
"\r\n" ) {
1298 $result = substr( $result, 0, -2 );
1299 } elseif ( substr( $result, -1 ) ===
"\n" ) {
1300 $result = substr( $result, 0, -1 );
1302 $this->
_handle_error( $sock,
'line ending missing in response from $1' );
1319 $n = stream_select( $r, $w, $e, 0, 0 );
1320 while ( $n == 1 && !feof( $f ) ) {
1325 $n = stream_select( $r, $w, $e, 0, 0 );
memcached client class implemented using (p)fsockopen()
set_debug( $dbg)
Set the debug flag.
array $_cache_sock
Cached Sockets that are connected.
const SERIALIZED
Flag: indicates data is serialized.
const COMPRESSION_SAVINGS
Minimum savings to store data compressed.
_hashfunc( $key)
Creates a hash integer based on the $key.
set_compress_threshold( $thresh)
Set the compression threshold.
_fread( $sock, $len)
Read the specified number of bytes from a stream.
array $_servers
Array containing ip:port or array(ip:port, weight)
bool $_compress_enable
Do we want to use compression?
decr( $key, $amt=1)
Decrease a value stored on the memcache server.
const INTVAL
Flag: indicates data is an integer.
int $_compress_threshold
At how many bytes should we compress?
int $_timeout_seconds
Stream timeout in seconds.
disconnect_all()
Disconnects all connected sockets.
cas( $casToken, $key, $value, $exp=0)
Sets a key to a given value in the memcache if the current value still corresponds to a known,...
array $_buckets
Our bit buckets.
set_timeout( $seconds, $microseconds)
Sets the timeout for new connections.
_fgets( $sock)
Read a line from a stream.
incr( $key, $amt=1)
Increments $key (optionally) by $amt.
forget_dead_hosts()
Forget about all of the dead hosts.
_incrdecr( $cmd, $key, $amt=1)
Perform increment/decriment on $key.
$_connect_attempts
Number of connection attempts for each server.
add( $key, $val, $exp=0)
Adds a key/value to the memcache server if one isn't already set with that key.
_handle_error( $sock, $msg)
Handle an I/O error.
sock_to_host( $host)
Returns the socket for the host.
$_connect_timeout
Connect timeout in seconds.
touch( $key, $time=0)
Changes the TTL on a key from the server to $time.
bool $_have_zlib
Is compression available?
int $_bucketcount
Total # of bit buckets we have.
_fwrite( $sock, $buf)
Write to a stream.
bool $_debug
Current debug status; 0 - none to 9 - profiling.
replace( $key, $value, $exp=0)
Overwrites an existing value for key; only works if key is already set.
set_servers( $list)
Set the server list to distribute key gets and puts between.
_load_items( $sock, &$ret, &$casToken=null)
Load items into $ret from $sock.
string $_single_sock
If only using one server; contains ip:port to connect to.
get_multi( $keys)
Get multiple keys from the server(s)
_close_sock( $sock)
Close the specified socket.
run_command( $sock, $cmd)
Passes through $cmd to the memcache server connected by $sock; returns output as an array (null array...
_set( $cmd, $key, $val, $exp, $casToken=null)
Performs the requested storage operation to the memcache server.
int $_timeout_microseconds
Stream timeout in microseconds.
__construct( $args)
Memcache initializer.
_flush_read_buffer( $f)
Flush the read buffer of a stream.
enable_compress( $enable)
Enable / Disable compression.
array $_host_dead
Dead hosts, assoc array, 'host'=>'unixtime when ok to check again'.
const COMPRESSED
Flag: indicates data is compressed.
_dead_sock( $sock)
Marks a host as dead until 30-40 seconds in the future.
_connect_sock(&$sock, $host)
Connects $sock to $host, timing out after $timeout.
array $stats
Command statistics.
bool $_persistent
Are we using persistent links?