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