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