<?php
    /*   
     Copyright (c) 2012, Paul G Talaga
     All rights reserved.
     
     Redistribution and use in source and binary forms, with or without
     modification, are permitted provided that the following conditions are met:
     * Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.
     * Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.
     
     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
     ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
     WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
     DISCLAIMED. IN NO EVENT SHALL Paul G Talaga BE LIABLE FOR ANY
     DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
     (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
     LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
     ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
     SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     */
    
    // Wrapper class to PECL memcache, which logs all memcache commands
    error_reporting(E_ALL);
    class Memcache_Logging extends Memcache{
        
        // constructor funciton
        function __construct(){
            $this->log = '';
            $this->unique = rand();
            $this->save_log = '/tmp/stress_validate_log.txt';
            $this->servers = array();
            $this->counter = 0;
        }
        
        function __destruct(){
            $this->save_log();
        }
        
        function save_log(){
            $fp = fopen($this->save_log,'a');
            flock($fp, LOCK_EX);
            fwrite($fp,$this->log); // Plain text output.  Consider compressing 
			//	for space.  Compressing each line isn't very efficient.
            flock($fp, LOCK_UN);
            fclose($fp);
            $this->log = '';
        }
        
        function log($cmd,$key,$out_len,$found,$params,$delay){
            $this->counter++;
            $cookie = var_export($_COOKIE,true);
            // 1/10 second accuracy for time
            if($key !== ''){$dest_srv = parent::findServer($key);}else{$dest_srv='all';}
            list($usec, $sec) = explode(" ", microtime());
            $time = $sec * 10 + round($usec * 10);
            $data = serialize(array($time,substr(md5($cookie),0,2), isset($_SERVER['SERVER_ADDR'])?$_SERVER['SERVER_ADDR']:'0.0.0.0',$dest_srv,$cmd,$key,$out_len,$found,$params,$delay,substr(md5($_SERVER["REQUEST_TIME"] . $_SERVER['SERVER_ADDR'] .  $_SERVER["REMOTE_ADDR"]),0,5)));
            
            $this->log .= $data . "\n" ;
        }
        
        function log_file($log){
            if($log){
                $this->save_log = $log;
            }
            return $this->save_log;
        }
        
        function add(&$key,&$value,$flags = 0,$expire = 0){
            $now = microtime(true);
            $result = parent::add($key,$value,$flags,$expire);
            self::log('add',$key, self::getNetlength($value), $result,serialize(array($flags,$expire)),microtime(true)-$now);    
            return $result;
        }

        function delete(&$key,$expire = 0){// TODO: Handle array
            $now = microtime(true);
            $data = parent::delete($key,$expire);
            self::log('delete',$key,0,$data,serialize(array($expire)),microtime(true)-$now);
            return $data;
        }
        
        function flush(){ // We should really find out how many memcache servers 
						  // there are to predict total network bytes sent
            $now = microtime(true);
            $return = parent::flush();
            self::log('flush','',0,'',serialize(array()),microtime(true)-$now);
            return $return;
        }
        function get(&$key,&$flags = null,&$cas = null){
            if(is_array($key)){ // multiget - we save everything as one entry, 
								// with overall time recorded
                $succ = array();    // the keys get saved as indexes to the 
									// destination server
                $lengths = array();
                $dest = array();
                $now = microtime(true);
                $data = parent::get($key,$flags,$cas);
                $i = 0;
                foreach ($data as $k => $v){
                    $key2[$i] = $k;
                    if($v === FALSE){$succ[$k] = FALSE;
                    }else{$succ[$i] = TRUE;}
                    $lengths[$i] = self::getNetlength($v);
                    $i++;
                }
                self::log('multiget',serialize($key2),serialize($lengths),serialize($succ),0,microtime(true)-$now); 
            }else{  //single get
                $now = microtime(true);
                $data = parent::get($key,$flags,$cas);
                self::log('get',$key,self::getNetlength($data),!($data === FALSE),serialize(array($flags,$cas)),microtime(true)-$now);
            }
            return $data;
        }
        function replace(&$key, &$value, $flags = 0,$expire = 0){
            $now = microtime(true);
            $result = parent::replace($key,$value,$flags,$expire);
            self::log('replace',$key,self::getNetlength($value), $result,serialize(array($flags,$expire)),microtime(true)-$now);
            return $result;
        }
        function decrement(&$key, $amt = 1){ // TODO: Handle array
            $now = microtime(true);
            $result = parent::decrement($key,$amt);
            self::log('decr',$key,self::getNetlength($amt) + self::getNetlength($result), $result,serialize(array()),microtime(true)-$now);
            return $result;
        }
        function increment(&$key, $amt = 1){ // TODO: Handle array
            $now = microtime(true);
            $result = parent::increment($key,$amt);
            self::log('incr',$key,self::getNetlength($amt) + self::getNetlength($result), $result,serialize(array()),microtime(true)-$now);
            return $result;
        }
        function set(&$key,&$value,$flags = 0,$expire = 0){
            $now = microtime(true);
            $result = parent::set($key,$value,$flags,$expire);
            if($result == FALSE){trigger_error("Set fail on $key");};
            self::log('set',$key,self::getNetlength($value), $result,serialize(array($flags,$expire)),microtime(true)-$now);    
            return $result;
        }
        function append(&$key,&$value,$flags = 0,$expire = 0){
            $now = microtime(true);
            $result = parent::append($key,$value,$flags,$expire);
            self::log('append',$key,self::getNetlength($value), $result,serialize(array($flags,$expire)),microtime(true)-$now);    
            return $result;
        }
        function prepend(&$key,&$value,$flags = 0,$expire = 0){
            $now = microtime(true);
            $result = parent::prepend($key,$value,$flags,$expire);
            self::log('prepend',$key,self::getNetlength($value), $result,serialize(array($flags,$expire)),microtime(true)-$now);    
            return $result;
        }
        
        function getNetlength(&$value){
            // returns the number of bytes which should be put on the wire for 
			//	this object
            if(is_string($value)){
                return strlen($value);
            }else if(is_int($value)){
                return strlen(strval($value)) + 2; // for flags
            }else if(is_float($value)){
                return strlen(sprintf('%.14g',$value)) + 3; // for flags
            }else if(is_bool($value)){
                return 1;  // 0 or 1
            }else{
                return strlen(serialize($value));
            }
        }
    }
?>
