Don't look for pipes in the root node.
[lhc/web/wiklou.git] / includes / memcached-client.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 * 'persistant' => 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 persistant links?
162 *
163 * @var boolean
164 * @access private
165 */
166 var $_persistant;
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 global $wgMemCachedTimeout;
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->_persistant = isset( $args['persistant'] ) ? $args['persistant'] : false;
254 $this->_compress_enable = true;
255 $this->_have_zlib = function_exists( 'gzcompress' );
256
257 $this->_cache_sock = array();
258 $this->_host_dead = array();
259
260 $this->_timeout_seconds = 0;
261 $this->_timeout_microseconds = $wgMemCachedTimeout;
262
263 $this->_connect_timeout = 0.01;
264 $this->_connect_attempts = 2;
265 }
266
267 // }}}
268 // {{{ add()
269
270 /**
271 * Adds a key/value to the memcache server if one isn't already set with
272 * that key
273 *
274 * @param $key String: 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 exipration
280 * eg: strtotime("+3 hour")
281 *
282 * @return Boolean
283 */
284 public function add( $key, $val, $exp = 0 ) {
285 return $this->_set( 'add', $key, $val, $exp );
286 }
287
288 // }}}
289 // {{{ decr()
290
291 /**
292 * Decrease a value stored on the memcache server
293 *
294 * @param $key String: key to decrease
295 * @param $amt Integer: (optional) amount to decrease
296 *
297 * @return Mixed: FALSE on failure, value on success
298 */
299 public function decr( $key, $amt = 1 ) {
300 return $this->_incrdecr( 'decr', $key, $amt );
301 }
302
303 // }}}
304 // {{{ delete()
305
306 /**
307 * Deletes a key from the server, optionally after $time
308 *
309 * @param $key String: key to delete
310 * @param $time Integer: (optional) how long to wait before deleting
311 *
312 * @return Boolean: TRUE on success, FALSE on failure
313 */
314 public function delete( $key, $time = 0 ) {
315 if ( !$this->_active ) {
316 return false;
317 }
318
319 $sock = $this->get_sock( $key );
320 if ( !is_resource( $sock ) ) {
321 return false;
322 }
323
324 $key = is_array( $key ) ? $key[1] : $key;
325
326 if ( isset( $this->stats['delete'] ) ) {
327 $this->stats['delete']++;
328 } else {
329 $this->stats['delete'] = 1;
330 }
331 $cmd = "delete $key $time\r\n";
332 if( !$this->_safe_fwrite( $sock, $cmd, strlen( $cmd ) ) ) {
333 $this->_dead_sock( $sock );
334 return false;
335 }
336 $res = trim( fgets( $sock ) );
337
338 if ( $this->_debug ) {
339 $this->_debugprint( sprintf( "MemCache: delete %s (%s)\n", $key, $res ) );
340 }
341
342 if ( $res == "DELETED" ) {
343 return true;
344 }
345 return false;
346 }
347
348 // }}}
349 // {{{ disconnect_all()
350
351 /**
352 * Disconnects all connected sockets
353 */
354 public function disconnect_all() {
355 foreach ( $this->_cache_sock as $sock ) {
356 fclose( $sock );
357 }
358
359 $this->_cache_sock = array();
360 }
361
362 // }}}
363 // {{{ enable_compress()
364
365 /**
366 * Enable / Disable compression
367 *
368 * @param $enable Boolean: TRUE to enable, FALSE to disable
369 */
370 public function enable_compress( $enable ) {
371 $this->_compress_enable = $enable;
372 }
373
374 // }}}
375 // {{{ forget_dead_hosts()
376
377 /**
378 * Forget about all of the dead hosts
379 */
380 public function forget_dead_hosts() {
381 $this->_host_dead = array();
382 }
383
384 // }}}
385 // {{{ get()
386
387 /**
388 * Retrieves the value associated with the key from the memcache server
389 *
390 * @param $key Mixed: key to retrieve
391 *
392 * @return Mixed
393 */
394 public function get( $key ) {
395 wfProfileIn( __METHOD__ );
396
397 if ( $this->_debug ) {
398 $this->_debugprint( "get($key)\n" );
399 }
400
401 if ( !$this->_active ) {
402 wfProfileOut( __METHOD__ );
403 return false;
404 }
405
406 $sock = $this->get_sock( $key );
407
408 if ( !is_resource( $sock ) ) {
409 wfProfileOut( __METHOD__ );
410 return false;
411 }
412
413 if ( isset( $this->stats['get'] ) ) {
414 $this->stats['get']++;
415 } else {
416 $this->stats['get'] = 1;
417 }
418
419 $cmd = "get $key\r\n";
420 if ( !$this->_safe_fwrite( $sock, $cmd, strlen( $cmd ) ) ) {
421 $this->_dead_sock( $sock );
422 wfProfileOut( __METHOD__ );
423 return false;
424 }
425
426 $val = array();
427 $this->_load_items( $sock, $val );
428
429 if ( $this->_debug ) {
430 foreach ( $val as $k => $v ) {
431 $this->_debugprint( sprintf( "MemCache: sock %s got %s\n", serialize( $sock ), $k ) );
432 }
433 }
434
435 wfProfileOut( __METHOD__ );
436 return @$val[$key];
437 }
438
439 // }}}
440 // {{{ get_multi()
441
442 /**
443 * Get multiple keys from the server(s)
444 *
445 * @param $keys Array: keys to retrieve
446 *
447 * @return Array
448 */
449 public function get_multi( $keys ) {
450 if ( !$this->_active ) {
451 return false;
452 }
453
454 if ( isset( $this->stats['get_multi'] ) ) {
455 $this->stats['get_multi']++;
456 } else {
457 $this->stats['get_multi'] = 1;
458 }
459 $sock_keys = array();
460
461 foreach ( $keys as $key ) {
462 $sock = $this->get_sock( $key );
463 if ( !is_resource( $sock ) ) {
464 continue;
465 }
466 $key = is_array( $key ) ? $key[1] : $key;
467 if ( !isset( $sock_keys[$sock] ) ) {
468 $sock_keys[$sock] = array();
469 $socks[] = $sock;
470 }
471 $sock_keys[$sock][] = $key;
472 }
473
474 // Send out the requests
475 foreach ( $socks as $sock ) {
476 $cmd = 'get';
477 foreach ( $sock_keys[$sock] as $key ) {
478 $cmd .= ' ' . $key;
479 }
480 $cmd .= "\r\n";
481
482 if ( $this->_safe_fwrite( $sock, $cmd, strlen( $cmd ) ) ) {
483 $gather[] = $sock;
484 } else {
485 $this->_dead_sock( $sock );
486 }
487 }
488
489 // Parse responses
490 $val = array();
491 foreach ( $gather as $sock ) {
492 $this->_load_items( $sock, $val );
493 }
494
495 if ( $this->_debug ) {
496 foreach ( $val as $k => $v ) {
497 $this->_debugprint( sprintf( "MemCache: got %s\n", $k ) );
498 }
499 }
500
501 return $val;
502 }
503
504 // }}}
505 // {{{ incr()
506
507 /**
508 * Increments $key (optionally) by $amt
509 *
510 * @param $key String: key to increment
511 * @param $amt Integer: (optional) amount to increment
512 *
513 * @return Integer: null if the key does not exist yet (this does NOT
514 * create new mappings if the key does not exist). If the key does
515 * exist, this returns the new value for that key.
516 */
517 public function incr( $key, $amt = 1 ) {
518 return $this->_incrdecr( 'incr', $key, $amt );
519 }
520
521 // }}}
522 // {{{ replace()
523
524 /**
525 * Overwrites an existing value for key; only works if key is already set
526 *
527 * @param $key String: key to set value as
528 * @param $value Mixed: value to store
529 * @param $exp Integer: (optional) Expiration time. This can be a number of seconds
530 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
531 * longer must be the timestamp of the time at which the mapping should expire. It
532 * is safe to use timestamps in all cases, regardless of exipration
533 * eg: strtotime("+3 hour")
534 *
535 * @return Boolean
536 */
537 public function replace( $key, $value, $exp = 0 ) {
538 return $this->_set( 'replace', $key, $value, $exp );
539 }
540
541 // }}}
542 // {{{ run_command()
543
544 /**
545 * Passes through $cmd to the memcache server connected by $sock; returns
546 * output as an array (null array if no output)
547 *
548 * NOTE: due to a possible bug in how PHP reads while using fgets(), each
549 * line may not be terminated by a \r\n. More specifically, my testing
550 * has shown that, on FreeBSD at least, each line is terminated only
551 * with a \n. This is with the PHP flag auto_detect_line_endings set
552 * to falase (the default).
553 *
554 * @param $sock Ressource: socket to send command on
555 * @param $cmd String: command to run
556 *
557 * @return Array: output array
558 */
559 public function run_command( $sock, $cmd ) {
560 if ( !is_resource( $sock ) ) {
561 return array();
562 }
563
564 if ( !$this->_safe_fwrite( $sock, $cmd, strlen( $cmd ) ) ) {
565 return array();
566 }
567
568 while ( true ) {
569 $res = fgets( $sock );
570 $ret[] = $res;
571 if ( preg_match( '/^END/', $res ) ) {
572 break;
573 }
574 if ( strlen( $res ) == 0 ) {
575 break;
576 }
577 }
578 return $ret;
579 }
580
581 // }}}
582 // {{{ set()
583
584 /**
585 * Unconditionally sets a key to a given value in the memcache. Returns true
586 * if set successfully.
587 *
588 * @param $key String: key to set value as
589 * @param $value Mixed: value to set
590 * @param $exp Integer: (optional) Expiration time. This can be a number of seconds
591 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
592 * longer must be the timestamp of the time at which the mapping should expire. It
593 * is safe to use timestamps in all cases, regardless of exipration
594 * eg: strtotime("+3 hour")
595 *
596 * @return Boolean: TRUE on success
597 */
598 public function set( $key, $value, $exp = 0 ) {
599 return $this->_set( 'set', $key, $value, $exp );
600 }
601
602 // }}}
603 // {{{ set_compress_threshold()
604
605 /**
606 * Sets the compression threshold
607 *
608 * @param $thresh Integer: threshold to compress if larger than
609 */
610 public function set_compress_threshold( $thresh ) {
611 $this->_compress_threshold = $thresh;
612 }
613
614 // }}}
615 // {{{ set_debug()
616
617 /**
618 * Sets the debug flag
619 *
620 * @param $dbg Boolean: TRUE for debugging, FALSE otherwise
621 *
622 * @see MWMemcached::__construct
623 */
624 public function set_debug( $dbg ) {
625 $this->_debug = $dbg;
626 }
627
628 // }}}
629 // {{{ set_servers()
630
631 /**
632 * Sets the server list to distribute key gets and puts between
633 *
634 * @param $list Array of servers to connect to
635 *
636 * @see MWMemcached::__construct()
637 */
638 public function set_servers( $list ) {
639 $this->_servers = $list;
640 $this->_active = count( $list );
641 $this->_buckets = null;
642 $this->_bucketcount = 0;
643
644 $this->_single_sock = null;
645 if ( $this->_active == 1 ) {
646 $this->_single_sock = $this->_servers[0];
647 }
648 }
649
650 /**
651 * Sets the timeout for new connections
652 *
653 * @param $seconds Integer: number of seconds
654 * @param $microseconds Integer: number of microseconds
655 */
656 public function set_timeout( $seconds, $microseconds ) {
657 $this->_timeout_seconds = $seconds;
658 $this->_timeout_microseconds = $microseconds;
659 }
660
661 // }}}
662 // }}}
663 // {{{ private methods
664 // {{{ _close_sock()
665
666 /**
667 * Close the specified socket
668 *
669 * @param $sock String: socket to close
670 *
671 * @access private
672 */
673 function _close_sock( $sock ) {
674 $host = array_search( $sock, $this->_cache_sock );
675 fclose( $this->_cache_sock[$host] );
676 unset( $this->_cache_sock[$host] );
677 }
678
679 // }}}
680 // {{{ _connect_sock()
681
682 /**
683 * Connects $sock to $host, timing out after $timeout
684 *
685 * @param $sock Integer: socket to connect
686 * @param $host String: Host:IP to connect to
687 *
688 * @return boolean
689 * @access private
690 */
691 function _connect_sock( &$sock, $host ) {
692 list( $ip, $port ) = explode( ':', $host );
693 $sock = false;
694 $timeout = $this->_connect_timeout;
695 $errno = $errstr = null;
696 for( $i = 0; !$sock && $i < $this->_connect_attempts; $i++ ) {
697 wfSuppressWarnings();
698 if ( $this->_persistant == 1 ) {
699 $sock = pfsockopen( $ip, $port, $errno, $errstr, $timeout );
700 } else {
701 $sock = fsockopen( $ip, $port, $errno, $errstr, $timeout );
702 }
703 wfRestoreWarnings();
704 }
705 if ( !$sock ) {
706 if ( $this->_debug ) {
707 $this->_debugprint( "Error connecting to $host: $errstr\n" );
708 }
709 return false;
710 }
711
712 // Initialise timeout
713 stream_set_timeout( $sock, $this->_timeout_seconds, $this->_timeout_microseconds );
714
715 return true;
716 }
717
718 // }}}
719 // {{{ _dead_sock()
720
721 /**
722 * Marks a host as dead until 30-40 seconds in the future
723 *
724 * @param $sock String: socket to mark as dead
725 *
726 * @access private
727 */
728 function _dead_sock( $sock ) {
729 $host = array_search( $sock, $this->_cache_sock );
730 $this->_dead_host( $host );
731 }
732
733 function _dead_host( $host ) {
734 $parts = explode( ':', $host );
735 $ip = $parts[0];
736 $this->_host_dead[$ip] = time() + 30 + intval( rand( 0, 10 ) );
737 $this->_host_dead[$host] = $this->_host_dead[$ip];
738 unset( $this->_cache_sock[$host] );
739 }
740
741 // }}}
742 // {{{ get_sock()
743
744 /**
745 * get_sock
746 *
747 * @param $key String: key to retrieve value for;
748 *
749 * @return Mixed: resource on success, false on failure
750 * @access private
751 */
752 function get_sock( $key ) {
753 if ( !$this->_active ) {
754 return false;
755 }
756
757 if ( $this->_single_sock !== null ) {
758 $this->_flush_read_buffer( $this->_single_sock );
759 return $this->sock_to_host( $this->_single_sock );
760 }
761
762 $hv = is_array( $key ) ? intval( $key[0] ) : $this->_hashfunc( $key );
763
764 if ( $this->_buckets === null ) {
765 foreach ( $this->_servers as $v ) {
766 if ( is_array( $v ) ) {
767 for( $i = 0; $i < $v[1]; $i++ ) {
768 $bu[] = $v[0];
769 }
770 } else {
771 $bu[] = $v;
772 }
773 }
774 $this->_buckets = $bu;
775 $this->_bucketcount = count( $bu );
776 }
777
778 $realkey = is_array( $key ) ? $key[1] : $key;
779 for( $tries = 0; $tries < 20; $tries++ ) {
780 $host = $this->_buckets[$hv % $this->_bucketcount];
781 $sock = $this->sock_to_host( $host );
782 if ( is_resource( $sock ) ) {
783 $this->_flush_read_buffer( $sock );
784 return $sock;
785 }
786 $hv = $this->_hashfunc( $hv . $realkey );
787 }
788
789 return false;
790 }
791
792 // }}}
793 // {{{ _hashfunc()
794
795 /**
796 * Creates a hash integer based on the $key
797 *
798 * @param $key String: key to hash
799 *
800 * @return Integer: hash value
801 * @access private
802 */
803 function _hashfunc( $key ) {
804 # Hash function must on [0,0x7ffffff]
805 # We take the first 31 bits of the MD5 hash, which unlike the hash
806 # function used in a previous version of this client, works
807 return hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
808 }
809
810 // }}}
811 // {{{ _incrdecr()
812
813 /**
814 * Perform increment/decriment on $key
815 *
816 * @param $cmd String: command to perform
817 * @param $key String: key to perform it on
818 * @param $amt Integer: amount to adjust
819 *
820 * @return Integer: new value of $key
821 * @access private
822 */
823 function _incrdecr( $cmd, $key, $amt = 1 ) {
824 if ( !$this->_active ) {
825 return null;
826 }
827
828 $sock = $this->get_sock( $key );
829 if ( !is_resource( $sock ) ) {
830 return null;
831 }
832
833 $key = is_array( $key ) ? $key[1] : $key;
834 if ( isset( $this->stats[$cmd] ) ) {
835 $this->stats[$cmd]++;
836 } else {
837 $this->stats[$cmd] = 1;
838 }
839 if ( !$this->_safe_fwrite( $sock, "$cmd $key $amt\r\n" ) ) {
840 return $this->_dead_sock( $sock );
841 }
842
843 $line = fgets( $sock );
844 $match = array();
845 if ( !preg_match( '/^(\d+)/', $line, $match ) ) {
846 return null;
847 }
848 return $match[1];
849 }
850
851 // }}}
852 // {{{ _load_items()
853
854 /**
855 * Load items into $ret from $sock
856 *
857 * @param $sock Ressource: socket to read from
858 * @param $ret Array: returned values
859 *
860 * @access private
861 */
862 function _load_items( $sock, &$ret ) {
863 while ( 1 ) {
864 $decl = fgets( $sock );
865 if ( $decl == "END\r\n" ) {
866 return true;
867 } elseif ( preg_match( '/^VALUE (\S+) (\d+) (\d+)\r\n$/', $decl, $match ) ) {
868 list( $rkey, $flags, $len ) = array( $match[1], $match[2], $match[3] );
869 $bneed = $len + 2;
870 $offset = 0;
871
872 while ( $bneed > 0 ) {
873 $data = fread( $sock, $bneed );
874 $n = strlen( $data );
875 if ( $n == 0 ) {
876 break;
877 }
878 $offset += $n;
879 $bneed -= $n;
880 if ( isset( $ret[$rkey] ) ) {
881 $ret[$rkey] .= $data;
882 } else {
883 $ret[$rkey] = $data;
884 }
885 }
886
887 if ( $offset != $len + 2 ) {
888 // Something is borked!
889 if ( $this->_debug ) {
890 $this->_debugprint( sprintf( "Something is borked! key %s expecting %d got %d length\n", $rkey, $len + 2, $offset ) );
891 }
892
893 unset( $ret[$rkey] );
894 $this->_close_sock( $sock );
895 return false;
896 }
897
898 if ( $this->_have_zlib && $flags & self::COMPRESSED ) {
899 $ret[$rkey] = gzuncompress( $ret[$rkey] );
900 }
901
902 $ret[$rkey] = rtrim( $ret[$rkey] );
903
904 if ( $flags & self::SERIALIZED ) {
905 $ret[$rkey] = unserialize( $ret[$rkey] );
906 }
907
908 } else {
909 $this->_debugprint( "Error parsing memcached response\n" );
910 return 0;
911 }
912 }
913 }
914
915 // }}}
916 // {{{ _set()
917
918 /**
919 * Performs the requested storage operation to the memcache server
920 *
921 * @param $cmd String: command to perform
922 * @param $key String: key to act on
923 * @param $val Mixed: what we need to store
924 * @param $exp Integer: (optional) Expiration time. This can be a number of seconds
925 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
926 * longer must be the timestamp of the time at which the mapping should expire. It
927 * is safe to use timestamps in all cases, regardless of exipration
928 * eg: strtotime("+3 hour")
929 *
930 * @return Boolean
931 * @access private
932 */
933 function _set( $cmd, $key, $val, $exp ) {
934 if ( !$this->_active ) {
935 return false;
936 }
937
938 $sock = $this->get_sock( $key );
939 if ( !is_resource( $sock ) ) {
940 return false;
941 }
942
943 if ( isset( $this->stats[$cmd] ) ) {
944 $this->stats[$cmd]++;
945 } else {
946 $this->stats[$cmd] = 1;
947 }
948
949 $flags = 0;
950
951 if ( !is_scalar( $val ) ) {
952 $val = serialize( $val );
953 $flags |= self::SERIALIZED;
954 if ( $this->_debug ) {
955 $this->_debugprint( sprintf( "client: serializing data as it is not scalar\n" ) );
956 }
957 }
958
959 $len = strlen( $val );
960
961 if ( $this->_have_zlib && $this->_compress_enable &&
962 $this->_compress_threshold && $len >= $this->_compress_threshold )
963 {
964 $c_val = gzcompress( $val, 9 );
965 $c_len = strlen( $c_val );
966
967 if ( $c_len < $len * ( 1 - self::COMPRESSION_SAVINGS ) ) {
968 if ( $this->_debug ) {
969 $this->_debugprint( sprintf( "client: compressing data; was %d bytes is now %d bytes\n", $len, $c_len ) );
970 }
971 $val = $c_val;
972 $len = $c_len;
973 $flags |= self::COMPRESSED;
974 }
975 }
976 if ( !$this->_safe_fwrite( $sock, "$cmd $key $flags $exp $len\r\n$val\r\n" ) ) {
977 return $this->_dead_sock( $sock );
978 }
979
980 $line = trim( fgets( $sock ) );
981
982 if ( $this->_debug ) {
983 $this->_debugprint( sprintf( "%s %s (%s)\n", $cmd, $key, $line ) );
984 }
985 if ( $line == "STORED" ) {
986 return true;
987 }
988 return false;
989 }
990
991 // }}}
992 // {{{ sock_to_host()
993
994 /**
995 * Returns the socket for the host
996 *
997 * @param $host String: Host:IP to get socket for
998 *
999 * @return Mixed: IO Stream or false
1000 * @access private
1001 */
1002 function sock_to_host( $host ) {
1003 if ( isset( $this->_cache_sock[$host] ) ) {
1004 return $this->_cache_sock[$host];
1005 }
1006
1007 $sock = null;
1008 $now = time();
1009 list( $ip, /* $port */) = explode( ':', $host );
1010 if ( isset( $this->_host_dead[$host] ) && $this->_host_dead[$host] > $now ||
1011 isset( $this->_host_dead[$ip] ) && $this->_host_dead[$ip] > $now
1012 ) {
1013 return null;
1014 }
1015
1016 if ( !$this->_connect_sock( $sock, $host ) ) {
1017 return $this->_dead_host( $host );
1018 }
1019
1020 // Do not buffer writes
1021 stream_set_write_buffer( $sock, 0 );
1022
1023 $this->_cache_sock[$host] = $sock;
1024
1025 return $this->_cache_sock[$host];
1026 }
1027
1028 function _debugprint( $str ) {
1029 print( $str );
1030 }
1031
1032 /**
1033 * Write to a stream, timing out after the correct amount of time
1034 *
1035 * @return Boolean: false on failure, true on success
1036 */
1037 /*
1038 function _safe_fwrite( $f, $buf, $len = false ) {
1039 stream_set_blocking( $f, 0 );
1040
1041 if ( $len === false ) {
1042 wfDebug( "Writing " . strlen( $buf ) . " bytes\n" );
1043 $bytesWritten = fwrite( $f, $buf );
1044 } else {
1045 wfDebug( "Writing $len bytes\n" );
1046 $bytesWritten = fwrite( $f, $buf, $len );
1047 }
1048 $n = stream_select( $r = null, $w = array( $f ), $e = null, 10, 0 );
1049 # $this->_timeout_seconds, $this->_timeout_microseconds );
1050
1051 wfDebug( "stream_select returned $n\n" );
1052 stream_set_blocking( $f, 1 );
1053 return $n == 1;
1054 return $bytesWritten;
1055 }*/
1056
1057 /**
1058 * Original behaviour
1059 */
1060 function _safe_fwrite( $f, $buf, $len = false ) {
1061 if ( $len === false ) {
1062 $bytesWritten = fwrite( $f, $buf );
1063 } else {
1064 $bytesWritten = fwrite( $f, $buf, $len );
1065 }
1066 return $bytesWritten;
1067 }
1068
1069 /**
1070 * Flush the read buffer of a stream
1071 */
1072 function _flush_read_buffer( $f ) {
1073 if ( !is_resource( $f ) ) {
1074 return;
1075 }
1076 $n = stream_select( $r = array( $f ), $w = null, $e = null, 0, 0 );
1077 while ( $n == 1 && !feof( $f ) ) {
1078 fread( $f, 1024 );
1079 $n = stream_select( $r = array( $f ), $w = null, $e = null, 0, 0 );
1080 }
1081 }
1082
1083 // }}}
1084 // }}}
1085 // }}}
1086 }
1087
1088 // vim: sts=3 sw=3 et
1089
1090 // }}}
1091
1092 class MemCachedClientforWiki extends MWMemcached {
1093 function _debugprint( $text ) {
1094 wfDebug( "memcached: $text" );
1095 }
1096 }