fnExecute = false; $t0 = microtime(); $rs =& $conn->Execute($sql,$inputarr); $t1 = microtime(); if (!empty($conn->_logsql)) { $conn->_logsql = false; // disable logsql error simulation $a0 = split(' ',$t0); $a0 = (float)$a0[1]+(float)$a0[0]; $a1 = split(' ',$t1); $a1 = (float)$a1[1]+(float)$a1[0]; $time = $a1 - $a0; if (!$rs) { $errM = $conn->ErrorMsg(); $errN = $conn->ErrorNo(); $tracer = substr('ERROR: '.htmlspecialchars($errM),0,250); } else { $tracer = ''; $errM = ''; $errN = 0; } if (isset($HTTP_SERVER_VARS['HTTP_HOST'])) { $tracer .= '
'.$HTTP_SERVER_VARS['HTTP_HOST']; if (isset($HTTP_SERVER_VARS['PHP_SELF'])) $tracer .= $HTTP_SERVER_VARS['PHP_SELF']; } else if (isset($HTTP_SERVER_VARS['PHP_SELF'])) $tracer .= '
'.$HTTP_SERVER_VARS['PHP_SELF']; //$tracer .= (string) adodb_backtrace(false); $tracer = substr($tracer,0,500); if (is_array($inputarr)) { if (is_array(reset($inputarr))) $params = 'Array sizeof='.sizeof($inputarr); else { $params = ''; $params = implode(', ',$inputarr); if (strlen($params) >= 3000) $params = substr($params, 0, 3000); } } else { $params = ''; } if (is_array($sql)) $sql = $sql[0]; $arr = array('b'=>trim(substr($sql,0,230)), 'c'=>substr($sql,0,3900), 'd'=>$params,'e'=>$tracer,'f'=>round($time,6)); $saved = $conn->debug; $conn->debug = 0; $dbT = $conn->databaseType; if ($conn->dataProvider == 'oci8' && $dbT != 'oci8po') { $isql = "insert into adodb_logsql values($conn->sysTimeStamp,:b,:c,:d,:e,:f)"; } else if ($dbT == 'odbc_mssql' || $dbT == 'informix') { $timer = $arr['f']; if ($dbT == 'informix') $sql2 = substr($sql2,0,230); $sql1 = $conn->qstr($arr['b']); $sql2 = $conn->qstr($arr['c']); $params = $conn->qstr($arr['d']); $tracer = $conn->qstr($arr['e']); $isql = "insert into adodb_logsql (created,sql0,sql1,params,tracer,timer) values($conn->sysTimeStamp,$sql1,$sql2,$params,$tracer,$timer)"; if ($dbT == 'informix') $isql = str_replace(chr(10),' ',$isql); $arr = false; } else { $isql = "insert into adodb_logsql (created,sql0,sql1,params,tracer,timer) values( $conn->sysTimeStamp,?,?,?,?,?)"; } $conn->_affected = $conn->affected_rows(true); $ok = $conn->Execute($isql,$arr); $conn->debug = $saved; if ($ok) { $conn->_logsql = true; } else { $err2 = $conn->ErrorMsg(); $conn->_logsql = true; // enable logsql error simulation $perf =& NewPerfMonitor($conn); if ($perf) { if ($perf->CreateLogTable()) $ok = $conn->Execute($isql,$arr); } else { $ok = $conn->Execute("create table adodb_logsql ( created varchar(50), sql0 varchar(250), sql1 varchar(4000), params varchar(3000), tracer varchar(500), timer decimal(16,6))"); } if (!$ok) { ADOConnection::outp( "LOGSQL Insert Failed: $isql
$err2
"); $conn->_logsql = false; } } $conn->_errorMsg = $errM; $conn->_errorCode = $errN; } $conn->fnExecute = 'adodb_log_sql'; return $rs; } /* The settings data structure is an associative array that database parameter per element. Each database parameter element in the array is itself an array consisting of: 0: category code, used to group related db parameters 1: either a. sql string to retrieve value, eg. "select value from v\$parameter where name='db_block_size'", b. array holding sql string and field to look for, e.g. array('show variables','table_cache'), c. a string prefixed by =, then a PHP method of the class is invoked, e.g. to invoke $this->GetIndexValue(), set this array element to '=GetIndexValue', 2: description of the database parameter */ class adodb_perf { var $conn; var $color = '#F0F0F0'; var $table = ''; var $titles = ''; var $warnRatio = 90; var $tablesSQL = false; var $cliFormat = "%32s => %s \r\n"; var $sql1 = 'sql1'; // used for casting sql1 to text for mssql var $explain = true; var $helpurl = "LogSQL help"; var $createTableSQL = false; // returns array with info to calculate CPU Load function _CPULoad() { /* cpu 524152 2662 2515228 336057010 cpu0 264339 1408 1257951 168025827 cpu1 259813 1254 1257277 168031181 page 622307 25475680 swap 24 1891 intr 890153570 868093576 6 0 4 4 0 6 1 2 0 0 0 124 0 8098760 2 13961053 0 0 0 0 0 0 0 0 0 0 0 0 0 16 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 disk_io: (3,0):(3144904,54369,610378,3090535,50936192) (3,1):(3630212,54097,633016,3576115,50951320) ctxt 66155838 btime 1062315585 processes 69293 */ // Algorithm is taken from // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/example__obtaining_raw_performance_data.asp if (strncmp(PHP_OS,'WIN',3)==0) { @$c = new COM("WinMgmts:{impersonationLevel=impersonate}!Win32_PerfRawData_PerfOS_Processor.Name='_Total'"); if (!$c) return false; $info[0] = $c->PercentProcessorTime; $info[1] = 0; $info[2] = 0; $info[3] = $c->TimeStamp_Sys100NS; //print_r($info); return $info; } // Algorithm - Steve Blinch (BlitzAffe Online, http://www.blitzaffe.com) $statfile = '/proc/stat'; if (!file_exists($statfile)) return false; $fd = fopen($statfile,"r"); if (!$fd) return false; $statinfo = explode("\n",fgets($fd, 1024)); fclose($fd); foreach($statinfo as $line) { $info = explode(" ",$line); if($info[0]=="cpu") { array_shift($info); // pop off "cpu" if(!$info[0]) array_shift($info); // pop off blank space (if any) return $info; } } return false; } /* NOT IMPLEMENTED */ function MemInfo() { /* total: used: free: shared: buffers: cached: Mem: 1055289344 917299200 137990144 0 165437440 599773184 Swap: 2146775040 11055104 2135719936 MemTotal: 1030556 kB MemFree: 134756 kB MemShared: 0 kB Buffers: 161560 kB Cached: 581384 kB SwapCached: 4332 kB Active: 494468 kB Inact_dirty: 322856 kB Inact_clean: 24256 kB Inact_target: 168316 kB HighTotal: 131064 kB HighFree: 1024 kB LowTotal: 899492 kB LowFree: 133732 kB SwapTotal: 2096460 kB SwapFree: 2085664 kB Committed_AS: 348732 kB */ } /* Remember that this is client load, not db server load! */ var $_lastLoad; function CPULoad() { $info = $this->_CPULoad(); if (!$info) return false; if (empty($this->_lastLoad)) { sleep(1); $this->_lastLoad = $info; $info = $this->_CPULoad(); } $last = $this->_lastLoad; $this->_lastLoad = $info; $d_user = $info[0] - $last[0]; $d_nice = $info[1] - $last[1]; $d_system = $info[2] - $last[2]; $d_idle = $info[3] - $last[3]; //printf("Delta - User: %f Nice: %f System: %f Idle: %f
",$d_user,$d_nice,$d_system,$d_idle); if (strncmp(PHP_OS,'WIN',3)==0) { if ($d_idle < 1) $d_idle = 1; return 100*(1-$d_user/$d_idle); }else { $total=$d_user+$d_nice+$d_system+$d_idle; if ($total<1) $total=1; return 100*($d_user+$d_nice+$d_system)/$total; } } function Tracer($sql) { $sqlq = $this->conn->qstr($sql); $arr = $this->conn->GetArray( "select count(*),tracer from adodb_logsql where sql1=$sqlq group by tracer order by 1 desc"); $s = ''; if ($arr) { $s .= '

Scripts Affected

'; foreach($arr as $k) { $s .= sprintf("%4d",$k[0]).'   '.strip_tags($k[1]).'
'; } } return $s; } function Explain($sql) { return false; } function InvalidSQL($numsql = 10) { global $HTTP_GET_VARS; if (isset($HTTP_GET_VARS['sql'])) return; $s = '

Invalid SQL

'; $saveE = $this->conn->fnExecute; $this->conn->fnExecute = false; $rs =& $this->conn->SelectLimit("select distinct count(*),sql1,tracer as error_msg from adodb_logsql where tracer like 'ERROR:%' group by sql1,tracer order by 1 desc",$numsql);//,$numsql); $this->conn->fnExecute = $saveE; if ($rs) { $s .= rs2html($rs,false,false,false,false); } else return "

$this->helpurl. ".$this->conn->ErrorMsg()."

"; return $s; } /* This script identifies the longest running SQL */ function _SuspiciousSQL($numsql = 10) { global $ADODB_FETCH_MODE,$HTTP_GET_VARS; $saveE = $this->conn->fnExecute; $this->conn->fnExecute = false; if (isset($HTTP_GET_VARS['exps']) && isset($HTTP_GET_VARS['sql'])) { echo "".$this->Explain($HTTP_GET_VARS['sql'])."\n"; } if (isset($HTTP_GET_VARS['sql'])) return; $sql1 = $this->sql1; $save = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; //$this->conn->debug=1; $rs =& $this->conn->SelectLimit( "select avg(timer) as avg_timer,$sql1,count(*),max(timer) as max_timer,min(timer) as min_timer from adodb_logsql where {$this->conn->upperCase}({$this->conn->substr}(sql0,1,5)) not in ('DROP ','INSER','COMMI','CREAT') and (tracer is null or tracer not like 'ERROR:%') group by sql1 order by 1 desc",$numsql); $ADODB_FETCH_MODE = $save; $this->conn->fnExecute = $saveE; if (!$rs) return "

$this->helpurl. ".$this->conn->ErrorMsg()."

"; $s = "

Suspicious SQL

The following SQL have high average execution times
ParameterValueDescription
\n"; while (!$rs->EOF) { $sql = trim($rs->fields[1]); $prefix = ""; $suffix = ""; if ($this->explain == false || strlen($prefix)>2000) { $prefix = ''; $suffix = ''; } $s .= ""; $rs->MoveNext(); } return $s."
Avg TimeCountSQLMaxMin
".round($rs->fields[0],6)."".$rs->fields[2]."".$prefix.htmlspecialchars($sql).$suffix."". "".$rs->fields[3]."".$rs->fields[4]."
"; } function CheckMemory() { return ''; } function SuspiciousSQL($numsql=10) { return adodb_perf::_SuspiciousSQL($numsql); } function ExpensiveSQL($numsql=10) { return adodb_perf::_ExpensiveSQL($numsql); } /* This reports the percentage of load on the instance due to the most expensive few SQL statements. Tuning these statements can often make huge improvements in overall system performance. */ function _ExpensiveSQL($numsql = 10) { global $HTTP_GET_VARS,$ADODB_FETCH_MODE; $saveE = $this->conn->fnExecute; $this->conn->fnExecute = false; if (isset($HTTP_GET_VARS['expe']) && isset($HTTP_GET_VARS['sql'])) { echo "".$this->Explain($HTTP_GET_VARS['sql'])."\n"; } if (isset($HTTP_GET_VARS['sql'])) return; $sql1 = $this->sql1; $save = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; $rs =& $this->conn->SelectLimit( "select sum(timer) as total,$sql1,count(*),max(timer) as max_timer,min(timer) as min_timer from adodb_logsql where {$this->conn->upperCase}({$this->conn->substr}(sql0,1,5)) not in ('DROP ','INSER','COMMI','CREAT') and (tracer is null or tracer not like 'ERROR:%') group by sql1 order by 1 desc",$numsql); $this->conn->fnExecute = $saveE; $ADODB_FETCH_MODE = $save; if (!$rs) return "

$this->helpurl. ".$this->conn->ErrorMsg()."

"; $s = "

Expensive SQL

Tuning the following SQL will reduce the server load substantially
\n"; while (!$rs->EOF) { $sql = $rs->fields[1]; $prefix = ""; $suffix = ""; if($this->explain == false || strlen($prefix>2000)) { $prefix = ''; $suffix = ''; } $s .= ""; $rs->MoveNext(); } return $s."
LoadCountSQLMaxMin
".round($rs->fields[0],6)."".$rs->fields[2]."".$prefix.htmlspecialchars($sql).$suffix."". "".$rs->fields[3]."".$rs->fields[4]."
"; } /* Raw function to return parameter value from $settings. */ function DBParameter($param) { if (empty($this->settings[$param])) return false; $sql = $this->settings[$param][1]; return $this->_DBParameter($sql); } /* Raw function returning array of poll paramters */ function &PollParameters() { $arr[0] = (float)$this->DBParameter('data cache hit ratio'); $arr[1] = (float)$this->DBParameter('data reads'); $arr[2] = (float)$this->DBParameter('data writes'); $arr[3] = (integer) $this->DBParameter('current connections'); return $arr; } /* Low-level Get Database Parameter */ function _DBParameter($sql) { $savelog = $this->conn->LogSQL(false); if (is_array($sql)) { global $ADODB_FETCH_MODE; $sql1 = $sql[0]; $key = $sql[1]; if (sizeof($sql)>2) $pos = $sql[2]; else $pos = 1; if (sizeof($sql)>3) $coef = $sql[3]; else $coef = false; $ret = false; $save = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; $rs = $this->conn->Execute($sql1); $ADODB_FETCH_MODE = $save; if ($rs) { while (!$rs->EOF) { $keyf = reset($rs->fields); if (trim($keyf) == $key) { $ret = $rs->fields[$pos]; if ($coef) $ret *= $coef; break; } $rs->MoveNext(); } $rs->Close(); } $this->conn->LogSQL($savelog); return $ret; } else { if (strncmp($sql,'=',1) == 0) { $fn = substr($sql,1); return $this->$fn(); } $sql = str_replace('$DATABASE',$this->conn->database,$sql); $ret = $this->conn->GetOne($sql); $this->conn->LogSQL($savelog); return $ret; } } /* Warn if cache ratio falls below threshold. Displayed in "Description" column. */ function WarnCacheRatio($val) { if ($val < $this->warnRatio) return 'Cache ratio should be at least '.$this->warnRatio.'%'; else return ''; } /***********************************************************************************************/ // HIGH LEVEL UI FUNCTIONS /***********************************************************************************************/ function UI($pollsecs=5) { global $HTTP_GET_VARS,$HTTP_SERVER_VARS; $conn = $this->conn; $app = $conn->host; if ($conn->host && $conn->database) $app .= ', db='; $app .= $conn->database; if ($app) $app .= ', '; $savelog = $this->conn->LogSQL(false); $info = $conn->ServerInfo(); if (isset($HTTP_GET_VARS['clearsql'])) { $this->conn->Execute('delete from adodb_logsql'); } $this->conn->LogSQL($savelog); // magic quotes if (isset($HTTP_GET_VARS['sql']) && get_magic_quotes_gpc()) { $_GET['sql'] = $HTTP_GET_VARS['sql'] = str_replace(array("\\'",'\"'),array("'",'"'),$HTTP_GET_VARS['sql']); } if (!isset($_SESSION['ADODB_PERF_SQL'])) $nsql = $_SESSION['ADODB_PERF_SQL'] = 10; else $nsql = $_SESSION['ADODB_PERF_SQL']; $app .= ''.$info['description'].''; if (isset($HTTP_GET_VARS['do'])) $do = $HTTP_GET_VARS['do']; else if (isset($HTTP_GET_VARS['sql'])) $do = 'viewsql'; else $do = 'stats'; if (isset($HTTP_GET_VARS['nsql'])) { if ($HTTP_GET_VARS['nsql'] > 0) $nsql = $_SESSION['ADODB_PERF_SQL'] = (integer) $HTTP_GET_VARS['nsql']; } echo "ADOdb Performance Monitor on $app"; if ($do == 'viewsql') $form = "
# SQL:
"; else $form = " "; if (empty($HTTP_GET_VARS['hidem'])) echo "
ADOdb Performance Monitor for $app
Performance Stats   View SQL   View Tables   Poll Stats", "$form", "
"; switch ($do) { default: case 'stats': echo $this->HealthCheck(); echo $this->CheckMemory(); break; case 'poll': echo ""; break; case 'poll2': echo "
";
			$this->Poll($pollsecs);
			break;
		case 'viewsql':
			if (empty($HTTP_GET_VARS['hidem']))
				echo "  Clear SQL Log
"; echo($this->SuspiciousSQL($nsql)); echo($this->ExpensiveSQL($nsql)); echo($this->InvalidSQL($nsql)); break; case 'tables': echo $this->Tables(); break; } global $ADODB_vers; echo "

$ADODB_vers Sponsored by phpLens
"; } /* Runs in infinite loop, returning real-time statistics */ function Poll($secs=5) { $this->conn->fnExecute = false; //$this->conn->debug=1; if ($secs <= 1) $secs = 1; echo "Accumulating statistics, every $secs seconds...\n";flush(); $arro =& $this->PollParameters(); $cnt = 0; set_time_limit(0); sleep($secs); while (1) { $arr =& $this->PollParameters(); $hits = sprintf('%2.2f',$arr[0]); $reads = sprintf('%12.4f',($arr[1]-$arro[1])/$secs); $writes = sprintf('%12.4f',($arr[2]-$arro[2])/$secs); $sess = sprintf('%5d',$arr[3]); $load = $this->CPULoad(); if ($load !== false) { $oslabel = 'WS-CPU%'; $osval = sprintf(" %2.1f ",(float) $load); }else { $oslabel = ''; $osval = ''; } if ($cnt % 10 == 0) echo " Time ".$oslabel." Hit% Sess Reads/s Writes/s\n"; $cnt += 1; echo date('H:i:s').' '.$osval."$hits $sess $reads $writes\n"; flush(); sleep($secs); $arro = $arr; } } /* Returns basic health check in a command line interface */ function HealthCheckCLI() { return $this->HealthCheck(true); } /* Returns basic health check as HTML */ function HealthCheck($cli=false) { $saveE = $this->conn->fnExecute; $this->conn->fnExecute = false; if ($cli) $html = ''; else $html = $this->table.'

'.$this->conn->databaseType.'

'.$this->titles; $oldc = false; $bgc = ''; foreach($this->settings as $name => $arr) { if ($arr === false) break; if (!is_string($name)) { if ($cli) $html .= " -- $arr -- \n"; else $html .= "color>$arr  "; continue; } if (!is_array($arr)) break; $category = $arr[0]; $how = $arr[1]; if (sizeof($arr)>2) $desc = $arr[2]; else $desc = '   '; if ($category == 'HIDE') continue; $val = $this->_DBParameter($how); if ($desc && strncmp($desc,"=",1) === 0) { $fn = substr($desc,1); $desc = $this->$fn($val); } if ($val === false) { $m = $this->conn->ErrorMsg(); $val = "Error: $m"; } else { if (is_numeric($val) && $val >= 256*1024) { if ($val % (1024*1024) == 0) { $val /= (1024*1024); $val .= 'M'; } else if ($val % 1024 == 0) { $val /= 1024; $val .= 'K'; } //$val = htmlspecialchars($val); } } if ($category != $oldc) { $oldc = $category; //$bgc = ($bgc == ' bgcolor='.$this->color) ? ' bgcolor=white' : ' bgcolor='.$this->color; } if (strlen($desc)==0) $desc = ' '; if (strlen($val)==0) $val = ' '; if ($cli) { $html .= str_replace(' ','',sprintf($this->cliFormat,strip_tags($name),strip_tags($val),strip_tags($desc))); }else { $html .= "".$name.''.$val.''.$desc."\n"; } } if (!$cli) $html .= "\n"; $this->conn->fnExecute = $saveE; return $html; } function Tables($orderby='1') { if (!$this->tablesSQL) return false; $savelog = $this->conn->LogSQL(false); $rs = $this->conn->Execute($this->tablesSQL.' order by '.$orderby); $this->conn->LogSQL($savelog); $html = rs2html($rs,false,false,false,false); return $html; } function CreateLogTable() { if (!$this->createTableSQL) return false; $savelog = $this->conn->LogSQL(false); $ok = $this->conn->Execute($this->createTableSQL); $this->conn->LogSQL($savelog); return ($ok) ? true : false; } } ?>