Bump RL filter version to 4 to keep it in sync with the cluster. WMF-centrism, I...
[lhc/web/wiklou.git] / includes / objectcache / MemcachedClient.php
1 <?php
2 /**
3 * +---------------------------------------------------------------------------+
4 * | memcached client, PHP |
5 * +---------------------------------------------------------------------------+
6 * | Copyright (c) 2003 Ryan T. Dean <rtdean@cytherianage.net> |
7 * | All rights reserved. |
8 * | |
9 * | Redistribution and use in source and binary forms, with or without |
10 * | modification, are permitted provided that the following conditions |
11 * | are met: |
12 * | |
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. |
18 * | |
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 * +---------------------------------------------------------------------------+
35 *
36 * @file
37 * $TCAnet$
38 */
39
40 /**
41 * This is the PHP client for memcached - a distributed memory cache daemon.
42 * More information is available at http://www.danga.com/memcached/
43 *
44 * Usage example:
45 *
46 * require_once 'memcached.php';
47 *
48 * $mc = new MWMemcached(array(
49 * 'servers' => array('127.0.0.1:10000',
50 * array('192.0.0.1:10010', 2),
51 * '127.0.0.1:10020'),
52 * 'debug' => false,
53 * 'compress_threshold' => 10240,
54 * 'persistent' => true));
55 *
56 * $mc->add('key', array('some', 'array'));
57 * $mc->replace('key', 'some random string');
58 * $val = $mc->get('key');
59 *
60 * @author Ryan T. Dean <rtdean@cytherianage.net>
61 * @version 0.1.2
62 */
63
64 // {{{ requirements
65 // }}}
66
67 // {{{ class MWMemcached
68 /**
69 * memcached client class implemented using (p)fsockopen()
70 *
71 * @author Ryan T. Dean <rtdean@cytherianage.net>
72 * @ingroup Cache
73 */
74 class MWMemcached {
75 // {{{ properties
76 // {{{ public
77
78 // {{{ constants
79 // {{{ flags
80
81 /**
82 * Flag: indicates data is serialized
83 */
84 const SERIALIZED = 1;
85
86 /**
87 * Flag: indicates data is compressed
88 */
89 const COMPRESSED = 2;
90
91 // }}}
92
93 /**
94 * Minimum savings to store data compressed
95 */
96 const COMPRESSION_SAVINGS = 0.20;
97
98 // }}}
99
100
101 /**
102 * Command statistics
103 *
104 * @var array
105 * @access public
106 */
107 var $stats;
108
109 // }}}
110 // {{{ private
111
112 /**
113 * Cached Sockets that are connected
114 *
115 * @var array
116 * @access private
117 */
118 var $_cache_sock;
119
120 /**
121 * Current debug status; 0 - none to 9 - profiling
122 *
123 * @var boolean
124 * @access private
125 */
126 var $_debug;
127
128 /**
129 * Dead hosts, assoc array, 'host'=>'unixtime when ok to check again'
130 *
131 * @var array
132 * @access private
133 */
134 var $_host_dead;
135
136 /**
137 * Is compression available?
138 *
139 * @var boolean
140 * @access private
141 */
142 var $_have_zlib;
143
144 /**
145 * Do we want to use compression?
146 *
147 * @var boolean
148 * @access private
149 */
150 var $_compress_enable;
151
152 /**
153 * At how many bytes should we compress?
154 *
155 * @var integer
156 * @access private
157 */
158 var $_compress_threshold;
159
160 /**
161 * Are we using persistent links?
162 *
163 * @var boolean
164 * @access private
165 */
166 var $_persistent;
167
168 /**
169 * If only using one server; contains ip:port to connect to
170 *
171 * @var string
172 * @access private
173 */
174 var $_single_sock;
175
176 /**
177 * Array containing ip:port or array(ip:port, weight)
178 *
179 * @var array
180 * @access private
181 */
182 var $_servers;
183
184 /**
185 * Our bit buckets
186 *
187 * @var array
188 * @access private
189 */
190 var $_buckets;
191
192 /**
193 * Total # of bit buckets we have
194 *
195 * @var integer
196 * @access private
197 */
198 var $_bucketcount;
199
200 /**
201 * # of total servers we have
202 *
203 * @var integer
204 * @access private
205 */
206 var $_active;
207
208 /**
209 * Stream timeout in seconds. Applies for example to fread()
210 *
211 * @var integer
212 * @access private
213 */
214 var $_timeout_seconds;
215
216 /**
217 * Stream timeout in microseconds
218 *
219 * @var integer
220 * @access private
221 */
222 var $_timeout_microseconds;
223
224 /**
225 * Connect timeout in seconds
226 */
227 var $_connect_timeout;
228
229 /**
230 * Number of connection attempts for each server
231 */
232 var $_connect_attempts;
233
234 // }}}
235 // }}}
236 // {{{ methods
237 // {{{ public functions
238 // {{{ memcached()
239
240 /**
241 * Memcache initializer
242 *
243 * @param $args Array Associative array of settings
244 *
245 * @return mixed
246 */
247 public function __construct( $args ) {
248 $this->set_servers( isset( $args['servers'] ) ? $args['servers'] : array() );
249 $this->_debug = isset( $args['debug'] ) ? $args['debug'] : false;
250 $this->stats = array();
251 $this->_compress_threshold = isset( $args['compress_threshold'] ) ? $args['compress_threshold'] : 0;
252 $this->_persistent = isset( $args['persistent'] ) ? $args['persistent'] : false;
253 $this->_compress_enable = true;
254 $this->_have_zlib = function_exists( 'gzcompress' );
255
256 $this->_cache_sock = array();
257 $this->_host_dead = array();
258
259 $this->_timeout_seconds = 0;
260 $this->_timeout_microseconds = isset( $args['timeout'] ) ? $args['timeout'] : 100000;
261
262 $this->_connect_timeout = isset( $args['connect_timeout'] ) ? $args['connect_timeout'] : 0.1;
263 $this->_connect_attempts = 2;
264 }
265
266 // }}}
267 // {{{ add()
268
269 /**
270 * Adds a key/value to the memcache server if one isn't already set with
271 * that key
272 *
273 * @param $key String: key to set with data
274 * @param $val Mixed: value to store
275 * @param $exp Integer: (optional) Expiration time. This can be a number of seconds
276 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
277 * longer must be the timestamp of the time at which the mapping should expire. It
278 * is safe to use timestamps in all cases, regardless of exipration
279 * eg: strtotime("+3 hour")
280 *
281 * @return Boolean
282 */
283 public function add( $key, $val, $exp = 0 ) {
284 return $this->_set( 'add', $key, $val, $exp );
285 }
286
287 // }}}
288 // {{{ decr()
289
290 /**
291 * Decrease a value stored on the memcache server
292 *
293 * @param $key String: key to decrease
294 * @param $amt Integer: (optional) amount to decrease
295 *
296 * @return Mixed: FALSE on failure, value on success
297 */
298 public function decr( $key, $amt = 1 ) {
299 return $this->_incrdecr( 'decr', $key, $amt );
300 }
301
302 // }}}
303 // {{{ delete()
304
305 /**
306 * Deletes a key from the server, optionally after $time
307 *
308 * @param $key String: key to delete
309 * @param $time Integer: (optional) how long to wait before deleting
310 *
311 * @return Boolean: TRUE on success, FALSE on failure
312 */
313 public function delete( $key, $time = 0 ) {
314 if ( !$this->_active ) {
315 return false;
316 }
317
318 $sock = $this->get_sock( $key );
319 if ( !is_resource( $sock ) ) {
320 return false;
321 }
322
323 $key = is_array( $key ) ? $key[1] : $key;
324
325 if ( isset( $this->stats['delete'] ) ) {
326 $this->stats['delete']++;
327 } else {
328 $this->stats['delete'] = 1;
329 }
330 $cmd = "delete $key $time\r\n";
331 if( !$this->_safe_fwrite( $sock, $cmd, strlen( $cmd ) ) ) {
332 $this->_dead_sock( $sock );
333 return false;
334 }
335 $res = trim( fgets( $sock ) );
336
337 if ( $this->_debug ) {
338 $this->_debugprint( sprintf( "MemCache: delete %s (%s)\n", $key, $res ) );
339 }
340
341 if ( $res == "DELETED" ) {
342 return true;
343 }
344 return false;
345 }
346
347 // }}}
348 // {{{ disconnect_all()
349
350 /**
351 * Disconnects all connected sockets
352 */
353 public function disconnect_all() {
354 foreach ( $this->_cache_sock as $sock ) {
355 fclose( $sock );
356 }
357
358 $this->_cache_sock = array();
359 }
360
361 // }}}
362 // {{{ enable_compress()
363
364 /**
365 * Enable / Disable compression
366 *
367 * @param $enable Boolean: TRUE to enable, FALSE to disable
368 */
369 public function enable_compress( $enable ) {
370 $this->_compress_enable = $enable;
371 }
372
373 // }}}
374 // {{{ forget_dead_hosts()
375
376 /**
377 * Forget about all of the dead hosts
378 */
379 public function forget_dead_hosts() {
380 $this->_host_dead = array();
381 }
382
383 // }}}
384 // {{{ get()
385
386 /**
387 * Retrieves the value associated with the key from the memcache server
388 *
389 * @param $key Mixed: key to retrieve
390 *
391 * @return Mixed
392 */
393 public function get( $key ) {
394 wfProfileIn( __METHOD__ );
395
396 if ( $this->_debug ) {
397 $this->_debugprint( "get($key)\n" );
398 }
399
400 if ( !$this->_active ) {
401 wfProfileOut( __METHOD__ );
402 return false;
403 }
404
405 $sock = $this->get_sock( $key );
406
407 if ( !is_resource( $sock ) ) {
408 wfProfileOut( __METHOD__ );
409 return false;
410 }
411
412 if ( isset( $this->stats['get'] ) ) {
413 $this->stats['get']++;
414 } else {
415 $this->stats['get'] = 1;
416 }
417
418 $cmd = "get $key\r\n";
419 if ( !$this->_safe_fwrite( $sock, $cmd, strlen( $cmd ) ) ) {
420 $this->_dead_sock( $sock );
421 wfProfileOut( __METHOD__ );
422 return false;
423 }
424
425 $val = array();
426 $this->_load_items( $sock, $val );
427
428 if ( $this->_debug ) {
429 foreach ( $val as $k => $v ) {
430 $this->_debugprint( sprintf( "MemCache: sock %s got %s\n", serialize( $sock ), $k ) );
431 }
432 }
433
434 $value = false;
435 if ( isset( $val[$key] ) ) {
436 $value = $val[$key];
437 }
438 wfProfileOut( __METHOD__ );
439 return $value;
440 }
441
442 // }}}
443 // {{{ get_multi()
444
445 /**
446 * Get multiple keys from the server(s)
447 *
448 * @param $keys Array: keys to retrieve
449 *
450 * @return Array
451 */
452 public function get_multi( $keys ) {
453 if ( !$this->_active ) {
454 return false;
455 }
456
457 if ( isset( $this->stats['get_multi'] ) ) {
458 $this->stats['get_multi']++;
459 } else {
460 $this->stats['get_multi'] = 1;
461 }
462 $sock_keys = array();
463
464 foreach ( $keys as $key ) {
465 $sock = $this->get_sock( $key );
466 if ( !is_resource( $sock ) ) {
467 continue;
468 }
469 $key = is_array( $key ) ? $key[1] : $key;
470 if ( !isset( $sock_keys[$sock] ) ) {
471 $sock_keys[$sock] = array();
472 $socks[] = $sock;
473 }
474 $sock_keys[$sock][] = $key;
475 }
476
477 // Send out the requests
478 foreach ( $socks as $sock ) {
479 $cmd = 'get';
480 foreach ( $sock_keys[$sock] as $key ) {
481 $cmd .= ' ' . $key;
482 }
483 $cmd .= "\r\n";
484
485 if ( $this->_safe_fwrite( $sock, $cmd, strlen( $cmd ) ) ) {
486 $gather[] = $sock;
487 } else {
488 $this->_dead_sock( $sock );
489 }
490 }
491
492 // Parse responses
493 $val = array();
494 foreach ( $gather as $sock ) {
495 $this->_load_items( $sock, $val );
496 }
497
498 if ( $this->_debug ) {
499 foreach ( $val as $k => $v ) {
500 $this->_debugprint( sprintf( "MemCache: got %s\n", $k ) );
501 }
502 }
503
504 return $val;
505 }
506
507 // }}}
508 // {{{ incr()
509
510 /**
511 * Increments $key (optionally) by $amt
512 *
513 * @param $key String: key to increment
514 * @param $amt Integer: (optional) amount to increment
515 *
516 * @return Integer: null if the key does not exist yet (this does NOT
517 * create new mappings if the key does not exist). If the key does
518 * exist, this returns the new value for that key.
519 */
520 public function incr( $key, $amt = 1 ) {
521 return $this->_incrdecr( 'incr', $key, $amt );
522 }
523
524 // }}}
525 // {{{ replace()
526
527 /**
528 * Overwrites an existing value for key; only works if key is already set
529 *
530 * @param $key String: key to set value as
531 * @param $value Mixed: value to store
532 * @param $exp Integer: (optional) Expiration time. This can be a number of seconds
533 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
534 * longer must be the timestamp of the time at which the mapping should expire. It
535 * is safe to use timestamps in all cases, regardless of exipration
536 * eg: strtotime("+3 hour")
537 *
538 * @return Boolean
539 */
540 public function replace( $key, $value, $exp = 0 ) {
541 return $this->_set( 'replace', $key, $value, $exp );
542 }
543
544 // }}}
545 // {{{ run_command()
546
547 /**
548 * Passes through $cmd to the memcache server connected by $sock; returns
549 * output as an array (null array if no output)
550 *
551 * NOTE: due to a possible bug in how PHP reads while using fgets(), each
552 * line may not be terminated by a \r\n. More specifically, my testing
553 * has shown that, on FreeBSD at least, each line is terminated only
554 * with a \n. This is with the PHP flag auto_detect_line_endings set
555 * to falase (the default).
556 *
557 * @param $sock Ressource: socket to send command on
558 * @param $cmd String: command to run
559 *
560 * @return Array: output array
561 */
562 public function run_command( $sock, $cmd ) {
563 if ( !is_resource( $sock ) ) {
564 return array();
565 }
566
567 if ( !$this->_safe_fwrite( $sock, $cmd, strlen( $cmd ) ) ) {
568 return array();
569 }
570
571 while ( true ) {
572 $res = fgets( $sock );
573 $ret[] = $res;
574 if ( preg_match( '/^END/', $res ) ) {
575 break;
576 }
577 if ( strlen( $res ) == 0 ) {
578 break;
579 }
580 }
581 return $ret;
582 }
583
584 // }}}
585 // {{{ set()
586
587 /**
588 * Unconditionally sets a key to a given value in the memcache. Returns true
589 * if set successfully.
590 *
591 * @param $key String: key to set value as
592 * @param $value Mixed: value to set
593 * @param $exp Integer: (optional) Expiration time. This can be a number of seconds
594 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
595 * longer must be the timestamp of the time at which the mapping should expire. It
596 * is safe to use timestamps in all cases, regardless of exipration
597 * eg: strtotime("+3 hour")
598 *
599 * @return Boolean: TRUE on success
600 */
601 public function set( $key, $value, $exp = 0 ) {
602 return $this->_set( 'set', $key, $value, $exp );
603 }
604
605 // }}}
606 // {{{ set_compress_threshold()
607
608 /**
609 * Sets the compression threshold
610 *
611 * @param $thresh Integer: threshold to compress if larger than
612 */
613 public function set_compress_threshold( $thresh ) {
614 $this->_compress_threshold = $thresh;
615 }
616
617 // }}}
618 // {{{ set_debug()
619
620 /**
621 * Sets the debug flag
622 *
623 * @param $dbg Boolean: TRUE for debugging, FALSE otherwise
624 *
625 * @see MWMemcached::__construct
626 */
627 public function set_debug( $dbg ) {
628 $this->_debug = $dbg;
629 }
630
631 // }}}
632 // {{{ set_servers()
633
634 /**
635 * Sets the server list to distribute key gets and puts between
636 *
637 * @param $list Array of servers to connect to
638 *
639 * @see MWMemcached::__construct()
640 */
641 public function set_servers( $list ) {
642 $this->_servers = $list;
643 $this->_active = count( $list );
644 $this->_buckets = null;
645 $this->_bucketcount = 0;
646
647 $this->_single_sock = null;
648 if ( $this->_active == 1 ) {
649 $this->_single_sock = $this->_servers[0];
650 }
651 }
652
653 /**
654 * Sets the timeout for new connections
655 *
656 * @param $seconds Integer: number of seconds
657 * @param $microseconds Integer: number of microseconds
658 */
659 public function set_timeout( $seconds, $microseconds ) {
660 $this->_timeout_seconds = $seconds;
661 $this->_timeout_microseconds = $microseconds;
662 }
663
664 // }}}
665 // }}}
666 // {{{ private methods
667 // {{{ _close_sock()
668
669 /**
670 * Close the specified socket
671 *
672 * @param $sock String: socket to close
673 *
674 * @access private
675 */
676 function _close_sock( $sock ) {
677 $host = array_search( $sock, $this->_cache_sock );
678 fclose( $this->_cache_sock[$host] );
679 unset( $this->_cache_sock[$host] );
680 }
681
682 // }}}
683 // {{{ _connect_sock()
684
685 /**
686 * Connects $sock to $host, timing out after $timeout
687 *
688 * @param $sock Integer: socket to connect
689 * @param $host String: Host:IP to connect to
690 *
691 * @return boolean
692 * @access private
693 */
694 function _connect_sock( &$sock, $host ) {
695 list( $ip, $port ) = explode( ':', $host );
696 $sock = false;
697 $timeout = $this->_connect_timeout;
698 $errno = $errstr = null;
699 for( $i = 0; !$sock && $i < $this->_connect_attempts; $i++ ) {
700 wfSuppressWarnings();
701 if ( $this->_persistent == 1 ) {
702 $sock = pfsockopen( $ip, $port, $errno, $errstr, $timeout );
703 } else {
704 $sock = fsockopen( $ip, $port, $errno, $errstr, $timeout );
705 }
706 wfRestoreWarnings();
707 }
708 if ( !$sock ) {
709 if ( $this->_debug ) {
710 $this->_debugprint( "Error connecting to $host: $errstr\n" );
711 }
712 return false;
713 }
714
715 // Initialise timeout
716 stream_set_timeout( $sock, $this->_timeout_seconds, $this->_timeout_microseconds );
717
718 return true;
719 }
720
721 // }}}
722 // {{{ _dead_sock()
723
724 /**
725 * Marks a host as dead until 30-40 seconds in the future
726 *
727 * @param $sock String: socket to mark as dead
728 *
729 * @access private
730 */
731 function _dead_sock( $sock ) {
732 $host = array_search( $sock, $this->_cache_sock );
733 $this->_dead_host( $host );
734 }
735
736 function _dead_host( $host ) {
737 $parts = explode( ':', $host );
738 $ip = $parts[0];
739 $this->_host_dead[$ip] = time() + 30 + intval( rand( 0, 10 ) );
740 $this->_host_dead[$host] = $this->_host_dead[$ip];
741 unset( $this->_cache_sock[$host] );
742 }
743
744 // }}}
745 // {{{ get_sock()
746
747 /**
748 * get_sock
749 *
750 * @param $key String: key to retrieve value for;
751 *
752 * @return Mixed: resource on success, false on failure
753 * @access private
754 */
755 function get_sock( $key ) {
756 if ( !$this->_active ) {
757 return false;
758 }
759
760 if ( $this->_single_sock !== null ) {
761 $this->_flush_read_buffer( $this->_single_sock );
762 return $this->sock_to_host( $this->_single_sock );
763 }
764
765 $hv = is_array( $key ) ? intval( $key[0] ) : $this->_hashfunc( $key );
766
767 if ( $this->_buckets === null ) {
768 foreach ( $this->_servers as $v ) {
769 if ( is_array( $v ) ) {
770 for( $i = 0; $i < $v[1]; $i++ ) {
771 $bu[] = $v[0];
772 }
773 } else {
774 $bu[] = $v;
775 }
776 }
777 $this->_buckets = $bu;
778 $this->_bucketcount = count( $bu );
779 }
780
781 $realkey = is_array( $key ) ? $key[1] : $key;
782 for( $tries = 0; $tries < 20; $tries++ ) {
783 $host = $this->_buckets[$hv % $this->_bucketcount];
784 $sock = $this->sock_to_host( $host );
785 if ( is_resource( $sock ) ) {
786 $this->_flush_read_buffer( $sock );
787 return $sock;
788 }
789 $hv = $this->_hashfunc( $hv . $realkey );
790 }
791
792 return false;
793 }
794
795 // }}}
796 // {{{ _hashfunc()
797
798 /**
799 * Creates a hash integer based on the $key
800 *
801 * @param $key String: key to hash
802 *
803 * @return Integer: hash value
804 * @access private
805 */
806 function _hashfunc( $key ) {
807 # Hash function must on [0,0x7ffffff]
808 # We take the first 31 bits of the MD5 hash, which unlike the hash
809 # function used in a previous version of this client, works
810 return hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
811 }
812
813 // }}}
814 // {{{ _incrdecr()
815
816 /**
817 * Perform increment/decriment on $key
818 *
819 * @param $cmd String: command to perform
820 * @param $key String: key to perform it on
821 * @param $amt Integer: amount to adjust
822 *
823 * @return Integer: new value of $key
824 * @access private
825 */
826 function _incrdecr( $cmd, $key, $amt = 1 ) {
827 if ( !$this->_active ) {
828 return null;
829 }
830
831 $sock = $this->get_sock( $key );
832 if ( !is_resource( $sock ) ) {
833 return null;
834 }
835
836 $key = is_array( $key ) ? $key[1] : $key;
837 if ( isset( $this->stats[$cmd] ) ) {
838 $this->stats[$cmd]++;
839 } else {
840 $this->stats[$cmd] = 1;
841 }
842 if ( !$this->_safe_fwrite( $sock, "$cmd $key $amt\r\n" ) ) {
843 return $this->_dead_sock( $sock );
844 }
845
846 $line = fgets( $sock );
847 $match = array();
848 if ( !preg_match( '/^(\d+)/', $line, $match ) ) {
849 return null;
850 }
851 return $match[1];
852 }
853
854 // }}}
855 // {{{ _load_items()
856
857 /**
858 * Load items into $ret from $sock
859 *
860 * @param $sock Ressource: socket to read from
861 * @param $ret Array: returned values
862 *
863 * @access private
864 */
865 function _load_items( $sock, &$ret ) {
866 while ( 1 ) {
867 $decl = fgets( $sock );
868 if ( $decl == "END\r\n" ) {
869 return true;
870 } elseif ( preg_match( '/^VALUE (\S+) (\d+) (\d+)\r\n$/', $decl, $match ) ) {
871 list( $rkey, $flags, $len ) = array( $match[1], $match[2], $match[3] );
872 $bneed = $len + 2;
873 $offset = 0;
874
875 while ( $bneed > 0 ) {
876 $data = fread( $sock, $bneed );
877 $n = strlen( $data );
878 if ( $n == 0 ) {
879 break;
880 }
881 $offset += $n;
882 $bneed -= $n;
883 if ( isset( $ret[$rkey] ) ) {
884 $ret[$rkey] .= $data;
885 } else {
886 $ret[$rkey] = $data;
887 }
888 }
889
890 if ( $offset != $len + 2 ) {
891 // Something is borked!
892 if ( $this->_debug ) {
893 $this->_debugprint( sprintf( "Something is borked! key %s expecting %d got %d length\n", $rkey, $len + 2, $offset ) );
894 }
895
896 unset( $ret[$rkey] );
897 $this->_close_sock( $sock );
898 return false;
899 }
900
901 if ( $this->_have_zlib && $flags & self::COMPRESSED ) {
902 $ret[$rkey] = gzuncompress( $ret[$rkey] );
903 }
904
905 $ret[$rkey] = rtrim( $ret[$rkey] );
906
907 if ( $flags & self::SERIALIZED ) {
908 $ret[$rkey] = unserialize( $ret[$rkey] );
909 }
910
911 } else {
912 $this->_debugprint( "Error parsing memcached response\n" );
913 return 0;
914 }
915 }
916 }
917
918 // }}}
919 // {{{ _set()
920
921 /**
922 * Performs the requested storage operation to the memcache server
923 *
924 * @param $cmd String: command to perform
925 * @param $key String: key to act on
926 * @param $val Mixed: what we need to store
927 * @param $exp Integer: (optional) Expiration time. This can be a number of seconds
928 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
929 * longer must be the timestamp of the time at which the mapping should expire. It
930 * is safe to use timestamps in all cases, regardless of exipration
931 * eg: strtotime("+3 hour")
932 *
933 * @return Boolean
934 * @access private
935 */
936 function _set( $cmd, $key, $val, $exp ) {
937 if ( !$this->_active ) {
938 return false;
939 }
940
941 $sock = $this->get_sock( $key );
942 if ( !is_resource( $sock ) ) {
943 return false;
944 }
945
946 if ( isset( $this->stats[$cmd] ) ) {
947 $this->stats[$cmd]++;
948 } else {
949 $this->stats[$cmd] = 1;
950 }
951
952 $flags = 0;
953
954 if ( !is_scalar( $val ) ) {
955 $val = serialize( $val );
956 $flags |= self::SERIALIZED;
957 if ( $this->_debug ) {
958 $this->_debugprint( sprintf( "client: serializing data as it is not scalar\n" ) );
959 }
960 }
961
962 $len = strlen( $val );
963
964 if ( $this->_have_zlib && $this->_compress_enable &&
965 $this->_compress_threshold && $len >= $this->_compress_threshold )
966 {
967 $c_val = gzcompress( $val, 9 );
968 $c_len = strlen( $c_val );
969
970 if ( $c_len < $len * ( 1 - self::COMPRESSION_SAVINGS ) ) {
971 if ( $this->_debug ) {
972 $this->_debugprint( sprintf( "client: compressing data; was %d bytes is now %d bytes\n", $len, $c_len ) );
973 }
974 $val = $c_val;
975 $len = $c_len;
976 $flags |= self::COMPRESSED;
977 }
978 }
979 if ( !$this->_safe_fwrite( $sock, "$cmd $key $flags $exp $len\r\n$val\r\n" ) ) {
980 return $this->_dead_sock( $sock );
981 }
982
983 $line = trim( fgets( $sock ) );
984
985 if ( $this->_debug ) {
986 $this->_debugprint( sprintf( "%s %s (%s)\n", $cmd, $key, $line ) );
987 }
988 if ( $line == "STORED" ) {
989 return true;
990 }
991 return false;
992 }
993
994 // }}}
995 // {{{ sock_to_host()
996
997 /**
998 * Returns the socket for the host
999 *
1000 * @param $host String: Host:IP to get socket for
1001 *
1002 * @return Mixed: IO Stream or false
1003 * @access private
1004 */
1005 function sock_to_host( $host ) {
1006 if ( isset( $this->_cache_sock[$host] ) ) {
1007 return $this->_cache_sock[$host];
1008 }
1009
1010 $sock = null;
1011 $now = time();
1012 list( $ip, /* $port */) = explode( ':', $host );
1013 if ( isset( $this->_host_dead[$host] ) && $this->_host_dead[$host] > $now ||
1014 isset( $this->_host_dead[$ip] ) && $this->_host_dead[$ip] > $now
1015 ) {
1016 return null;
1017 }
1018
1019 if ( !$this->_connect_sock( $sock, $host ) ) {
1020 return $this->_dead_host( $host );
1021 }
1022
1023 // Do not buffer writes
1024 stream_set_write_buffer( $sock, 0 );
1025
1026 $this->_cache_sock[$host] = $sock;
1027
1028 return $this->_cache_sock[$host];
1029 }
1030
1031 function _debugprint( $str ) {
1032 print( $str );
1033 }
1034
1035 /**
1036 * Write to a stream, timing out after the correct amount of time
1037 *
1038 * @return Boolean: false on failure, true on success
1039 */
1040 /*
1041 function _safe_fwrite( $f, $buf, $len = false ) {
1042 stream_set_blocking( $f, 0 );
1043
1044 if ( $len === false ) {
1045 wfDebug( "Writing " . strlen( $buf ) . " bytes\n" );
1046 $bytesWritten = fwrite( $f, $buf );
1047 } else {
1048 wfDebug( "Writing $len bytes\n" );
1049 $bytesWritten = fwrite( $f, $buf, $len );
1050 }
1051 $n = stream_select( $r = null, $w = array( $f ), $e = null, 10, 0 );
1052 # $this->_timeout_seconds, $this->_timeout_microseconds );
1053
1054 wfDebug( "stream_select returned $n\n" );
1055 stream_set_blocking( $f, 1 );
1056 return $n == 1;
1057 return $bytesWritten;
1058 }*/
1059
1060 /**
1061 * Original behaviour
1062 */
1063 function _safe_fwrite( $f, $buf, $len = false ) {
1064 if ( $len === false ) {
1065 $bytesWritten = fwrite( $f, $buf );
1066 } else {
1067 $bytesWritten = fwrite( $f, $buf, $len );
1068 }
1069 return $bytesWritten;
1070 }
1071
1072 /**
1073 * Flush the read buffer of a stream
1074 */
1075 function _flush_read_buffer( $f ) {
1076 if ( !is_resource( $f ) ) {
1077 return;
1078 }
1079 $n = stream_select( $r = array( $f ), $w = null, $e = null, 0, 0 );
1080 while ( $n == 1 && !feof( $f ) ) {
1081 fread( $f, 1024 );
1082 $n = stream_select( $r = array( $f ), $w = null, $e = null, 0, 0 );
1083 }
1084 }
1085
1086 // }}}
1087 // }}}
1088 // }}}
1089 }
1090
1091 // vim: sts=3 sw=3 et
1092
1093 // }}}
1094
1095 class MemCachedClientforWiki extends MWMemcached {
1096 function _debugprint( $text ) {
1097 wfDebug( "memcached: $text" );
1098 }
1099 }