PageRenderTime 87ms CodeModel.GetById 49ms RepoModel.GetById 1ms app.codeStats 0ms

/libs/adodb/adodb-perf.inc.php

https://github.com/Fusion/lenses
PHP | 1088 lines | 878 code | 94 blank | 116 comment | 132 complexity | cc5002216afa92826a44d3847383a191 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. /*
  3. V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
  4. Released under both BSD license and Lesser GPL library license.
  5. Whenever there is any discrepancy between the two licenses,
  6. the BSD license will take precedence. See License.txt.
  7. Set tabs to 4 for best viewing.
  8. Latest version is available at http://adodb.sourceforge.net
  9. Library for basic performance monitoring and tuning.
  10. My apologies if you see code mixed with presentation. The presentation suits
  11. my needs. If you want to separate code from presentation, be my guest. Patches
  12. are welcome.
  13. */
  14. if (!defined('ADODB_DIR')) include_once(dirname(__FILE__).'/adodb.inc.php');
  15. include_once(ADODB_DIR.'/tohtml.inc.php');
  16. define( 'ADODB_OPT_HIGH', 2);
  17. define( 'ADODB_OPT_LOW', 1);
  18. global $ADODB_PERF_MIN;
  19. $ADODB_PERF_MIN = 0.05; // log only if >= minimum number of secs to run
  20. // returns in K the memory of current process, or 0 if not known
  21. function adodb_getmem()
  22. {
  23. if (function_exists('memory_get_usage'))
  24. return (integer) ((memory_get_usage()+512)/1024);
  25. $pid = getmypid();
  26. if ( strncmp(strtoupper(PHP_OS),'WIN',3)==0) {
  27. $output = array();
  28. exec('tasklist /FI "PID eq ' . $pid. '" /FO LIST', $output);
  29. return substr($output[5], strpos($output[5], ':') + 1);
  30. }
  31. /* Hopefully UNIX */
  32. exec("ps --pid $pid --no-headers -o%mem,size", $output);
  33. if (sizeof($output) == 0) return 0;
  34. $memarr = explode(' ',$output[0]);
  35. if (sizeof($memarr)>=2) return (integer) $memarr[1];
  36. return 0;
  37. }
  38. // avoids localization problems where , is used instead of .
  39. function adodb_round($n,$prec)
  40. {
  41. return number_format($n, $prec, '.', '');
  42. }
  43. /* return microtime value as a float */
  44. function adodb_microtime()
  45. {
  46. $t = microtime();
  47. $t = explode(' ',$t);
  48. return (float)$t[1]+ (float)$t[0];
  49. }
  50. /* sql code timing */
  51. function adodb_log_sql(&$connx,$sql,$inputarr)
  52. {
  53. $perf_table = adodb_perf::table();
  54. $connx->fnExecute = false;
  55. $t0 = microtime();
  56. $rs = $connx->Execute($sql,$inputarr);
  57. $t1 = microtime();
  58. if (!empty($connx->_logsql) && (empty($connx->_logsqlErrors) || !$rs)) {
  59. global $ADODB_LOG_CONN;
  60. if (!empty($ADODB_LOG_CONN)) {
  61. $conn = $ADODB_LOG_CONN;
  62. if ($conn->databaseType != $connx->databaseType)
  63. $prefix = '/*dbx='.$connx->databaseType .'*/ ';
  64. else
  65. $prefix = '';
  66. } else {
  67. $conn = $connx;
  68. $prefix = '';
  69. }
  70. $conn->_logsql = false; // disable logsql error simulation
  71. $dbT = $conn->databaseType;
  72. $a0 = split(' ',$t0);
  73. $a0 = (float)$a0[1]+(float)$a0[0];
  74. $a1 = split(' ',$t1);
  75. $a1 = (float)$a1[1]+(float)$a1[0];
  76. $time = $a1 - $a0;
  77. if (!$rs) {
  78. $errM = $connx->ErrorMsg();
  79. $errN = $connx->ErrorNo();
  80. $conn->lastInsID = 0;
  81. $tracer = substr('ERROR: '.htmlspecialchars($errM),0,250);
  82. } else {
  83. $tracer = '';
  84. $errM = '';
  85. $errN = 0;
  86. $dbg = $conn->debug;
  87. $conn->debug = false;
  88. if (!is_object($rs) || $rs->dataProvider == 'empty')
  89. $conn->_affected = $conn->affected_rows(true);
  90. $conn->lastInsID = @$conn->Insert_ID();
  91. $conn->debug = $dbg;
  92. }
  93. if (isset($_SERVER['HTTP_HOST'])) {
  94. $tracer .= '<br>'.$_SERVER['HTTP_HOST'];
  95. if (isset($_SERVER['PHP_SELF'])) $tracer .= $_SERVER['PHP_SELF'];
  96. } else
  97. if (isset($_SERVER['PHP_SELF'])) $tracer .= '<br>'.$_SERVER['PHP_SELF'];
  98. //$tracer .= (string) adodb_backtrace(false);
  99. $tracer = (string) substr($tracer,0,500);
  100. if (is_array($inputarr)) {
  101. if (is_array(reset($inputarr))) $params = 'Array sizeof='.sizeof($inputarr);
  102. else {
  103. // Quote string parameters so we can see them in the
  104. // performance stats. This helps spot disabled indexes.
  105. $xar_params = $inputarr;
  106. foreach ($xar_params as $xar_param_key => $xar_param) {
  107. if (gettype($xar_param) == 'string')
  108. $xar_params[$xar_param_key] = '"' . $xar_param . '"';
  109. }
  110. $params = implode(', ', $xar_params);
  111. if (strlen($params) >= 3000) $params = substr($params, 0, 3000);
  112. }
  113. } else {
  114. $params = '';
  115. }
  116. if (is_array($sql)) $sql = $sql[0];
  117. if ($prefix) $sql = $prefix.$sql;
  118. $arr = array('b'=>strlen($sql).'.'.crc32($sql),
  119. 'c'=>substr($sql,0,3900), 'd'=>$params,'e'=>$tracer,'f'=>adodb_round($time,6));
  120. //var_dump($arr);
  121. $saved = $conn->debug;
  122. $conn->debug = 0;
  123. $d = $conn->sysTimeStamp;
  124. if (empty($d)) $d = date("'Y-m-d H:i:s'");
  125. if ($conn->dataProvider == 'oci8' && $dbT != 'oci8po') {
  126. $isql = "insert into $perf_table values($d,:b,:c,:d,:e,:f)";
  127. } else if ($dbT == 'odbc_mssql' || $dbT == 'informix' || strncmp($dbT,'odbtp',4)==0) {
  128. $timer = $arr['f'];
  129. if ($dbT == 'informix') $sql2 = substr($sql2,0,230);
  130. $sql1 = $conn->qstr($arr['b']);
  131. $sql2 = $conn->qstr($arr['c']);
  132. $params = $conn->qstr($arr['d']);
  133. $tracer = $conn->qstr($arr['e']);
  134. $isql = "insert into $perf_table (created,sql0,sql1,params,tracer,timer) values($d,$sql1,$sql2,$params,$tracer,$timer)";
  135. if ($dbT == 'informix') $isql = str_replace(chr(10),' ',$isql);
  136. $arr = false;
  137. } else {
  138. if ($dbT == 'db2') $arr['f'] = (float) $arr['f'];
  139. $isql = "insert into $perf_table (created,sql0,sql1,params,tracer,timer) values( $d,?,?,?,?,?)";
  140. }
  141. global $ADODB_PERF_MIN;
  142. if ($errN != 0 || $time >= $ADODB_PERF_MIN) {
  143. $ok = $conn->Execute($isql,$arr);
  144. } else
  145. $ok = true;
  146. $conn->debug = $saved;
  147. if ($ok) {
  148. $conn->_logsql = true;
  149. } else {
  150. $err2 = $conn->ErrorMsg();
  151. $conn->_logsql = true; // enable logsql error simulation
  152. $perf = NewPerfMonitor($conn);
  153. if ($perf) {
  154. if ($perf->CreateLogTable()) $ok = $conn->Execute($isql,$arr);
  155. } else {
  156. $ok = $conn->Execute("create table $perf_table (
  157. created varchar(50),
  158. sql0 varchar(250),
  159. sql1 varchar(4000),
  160. params varchar(3000),
  161. tracer varchar(500),
  162. timer decimal(16,6))");
  163. }
  164. if (!$ok) {
  165. ADOConnection::outp( "<p><b>LOGSQL Insert Failed</b>: $isql<br>$err2</p>");
  166. $conn->_logsql = false;
  167. }
  168. }
  169. $connx->_errorMsg = $errM;
  170. $connx->_errorCode = $errN;
  171. }
  172. $connx->fnExecute = 'adodb_log_sql';
  173. return $rs;
  174. }
  175. /*
  176. The settings data structure is an associative array that database parameter per element.
  177. Each database parameter element in the array is itself an array consisting of:
  178. 0: category code, used to group related db parameters
  179. 1: either
  180. a. sql string to retrieve value, eg. "select value from v\$parameter where name='db_block_size'",
  181. b. array holding sql string and field to look for, e.g. array('show variables','table_cache'),
  182. c. a string prefixed by =, then a PHP method of the class is invoked,
  183. e.g. to invoke $this->GetIndexValue(), set this array element to '=GetIndexValue',
  184. 2: description of the database parameter
  185. */
  186. class adodb_perf {
  187. var $conn;
  188. var $color = '#F0F0F0';
  189. var $table = '<table border=1 bgcolor=white>';
  190. var $titles = '<tr><td><b>Parameter</b></td><td><b>Value</b></td><td><b>Description</b></td></tr>';
  191. var $warnRatio = 90;
  192. var $tablesSQL = false;
  193. var $cliFormat = "%32s => %s \r\n";
  194. var $sql1 = 'sql1'; // used for casting sql1 to text for mssql
  195. var $explain = true;
  196. var $helpurl = "<a href=http://phplens.com/adodb/reference.functions.fnexecute.and.fncacheexecute.properties.html#logsql>LogSQL help</a>";
  197. var $createTableSQL = false;
  198. var $maxLength = 2000;
  199. // Sets the tablename to be used
  200. static function table($newtable = false)
  201. {
  202. static $_table;
  203. if (!empty($newtable)) $_table = $newtable;
  204. if (empty($_table)) $_table = 'adodb_logsql';
  205. return $_table;
  206. }
  207. // returns array with info to calculate CPU Load
  208. function _CPULoad()
  209. {
  210. /*
  211. cpu 524152 2662 2515228 336057010
  212. cpu0 264339 1408 1257951 168025827
  213. cpu1 259813 1254 1257277 168031181
  214. page 622307 25475680
  215. swap 24 1891
  216. 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
  217. disk_io: (3,0):(3144904,54369,610378,3090535,50936192) (3,1):(3630212,54097,633016,3576115,50951320)
  218. ctxt 66155838
  219. btime 1062315585
  220. processes 69293
  221. */
  222. // Algorithm is taken from
  223. // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/example__obtaining_raw_performance_data.asp
  224. if (strncmp(PHP_OS,'WIN',3)==0) {
  225. if (PHP_VERSION == '5.0.0') return false;
  226. if (PHP_VERSION == '5.0.1') return false;
  227. if (PHP_VERSION == '5.0.2') return false;
  228. if (PHP_VERSION == '5.0.3') return false;
  229. if (PHP_VERSION == '4.3.10') return false; # see http://bugs.php.net/bug.php?id=31737
  230. @$c = new COM("WinMgmts:{impersonationLevel=impersonate}!Win32_PerfRawData_PerfOS_Processor.Name='_Total'");
  231. if (!$c) return false;
  232. $info[0] = $c->PercentProcessorTime;
  233. $info[1] = 0;
  234. $info[2] = 0;
  235. $info[3] = $c->TimeStamp_Sys100NS;
  236. //print_r($info);
  237. return $info;
  238. }
  239. // Algorithm - Steve Blinch (BlitzAffe Online, http://www.blitzaffe.com)
  240. $statfile = '/proc/stat';
  241. if (!file_exists($statfile)) return false;
  242. $fd = fopen($statfile,"r");
  243. if (!$fd) return false;
  244. $statinfo = explode("\n",fgets($fd, 1024));
  245. fclose($fd);
  246. foreach($statinfo as $line) {
  247. $info = explode(" ",$line);
  248. if($info[0]=="cpu") {
  249. array_shift($info); // pop off "cpu"
  250. if(!$info[0]) array_shift($info); // pop off blank space (if any)
  251. return $info;
  252. }
  253. }
  254. return false;
  255. }
  256. /* NOT IMPLEMENTED */
  257. function MemInfo()
  258. {
  259. /*
  260. total: used: free: shared: buffers: cached:
  261. Mem: 1055289344 917299200 137990144 0 165437440 599773184
  262. Swap: 2146775040 11055104 2135719936
  263. MemTotal: 1030556 kB
  264. MemFree: 134756 kB
  265. MemShared: 0 kB
  266. Buffers: 161560 kB
  267. Cached: 581384 kB
  268. SwapCached: 4332 kB
  269. Active: 494468 kB
  270. Inact_dirty: 322856 kB
  271. Inact_clean: 24256 kB
  272. Inact_target: 168316 kB
  273. HighTotal: 131064 kB
  274. HighFree: 1024 kB
  275. LowTotal: 899492 kB
  276. LowFree: 133732 kB
  277. SwapTotal: 2096460 kB
  278. SwapFree: 2085664 kB
  279. Committed_AS: 348732 kB
  280. */
  281. }
  282. /*
  283. Remember that this is client load, not db server load!
  284. */
  285. var $_lastLoad;
  286. function CPULoad()
  287. {
  288. $info = $this->_CPULoad();
  289. if (!$info) return false;
  290. if (empty($this->_lastLoad)) {
  291. sleep(1);
  292. $this->_lastLoad = $info;
  293. $info = $this->_CPULoad();
  294. }
  295. $last = $this->_lastLoad;
  296. $this->_lastLoad = $info;
  297. $d_user = $info[0] - $last[0];
  298. $d_nice = $info[1] - $last[1];
  299. $d_system = $info[2] - $last[2];
  300. $d_idle = $info[3] - $last[3];
  301. //printf("Delta - User: %f Nice: %f System: %f Idle: %f<br>",$d_user,$d_nice,$d_system,$d_idle);
  302. if (strncmp(PHP_OS,'WIN',3)==0) {
  303. if ($d_idle < 1) $d_idle = 1;
  304. return 100*(1-$d_user/$d_idle);
  305. }else {
  306. $total=$d_user+$d_nice+$d_system+$d_idle;
  307. if ($total<1) $total=1;
  308. return 100*($d_user+$d_nice+$d_system)/$total;
  309. }
  310. }
  311. function Tracer($sql)
  312. {
  313. $perf_table = adodb_perf::table();
  314. $saveE = $this->conn->fnExecute;
  315. $this->conn->fnExecute = false;
  316. global $ADODB_FETCH_MODE;
  317. $save = $ADODB_FETCH_MODE;
  318. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  319. if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
  320. $sqlq = $this->conn->qstr($sql);
  321. $arr = $this->conn->GetArray(
  322. "select count(*),tracer
  323. from $perf_table where sql1=$sqlq
  324. group by tracer
  325. order by 1 desc");
  326. $s = '';
  327. if ($arr) {
  328. $s .= '<h3>Scripts Affected</h3>';
  329. foreach($arr as $k) {
  330. $s .= sprintf("%4d",$k[0]).' &nbsp; '.strip_tags($k[1]).'<br>';
  331. }
  332. }
  333. if (isset($savem)) $this->conn->SetFetchMode($savem);
  334. $ADODB_CACHE_MODE = $save;
  335. $this->conn->fnExecute = $saveE;
  336. return $s;
  337. }
  338. /*
  339. Explain Plan for $sql.
  340. If only a snippet of the $sql is passed in, then $partial will hold the crc32 of the
  341. actual sql.
  342. */
  343. function Explain($sql,$partial=false)
  344. {
  345. return false;
  346. }
  347. function InvalidSQL($numsql = 10)
  348. {
  349. if (isset($_GET['sql'])) return;
  350. $s = '<h3>Invalid SQL</h3>';
  351. $saveE = $this->conn->fnExecute;
  352. $this->conn->fnExecute = false;
  353. $perf_table = adodb_perf::table();
  354. $rs = $this->conn->SelectLimit("select distinct count(*),sql1,tracer as error_msg from $perf_table where tracer like 'ERROR:%' group by sql1,tracer order by 1 desc",$numsql);//,$numsql);
  355. $this->conn->fnExecute = $saveE;
  356. if ($rs) {
  357. $s .= rs2html($rs,false,false,false,false);
  358. } else
  359. return "<p>$this->helpurl. ".$this->conn->ErrorMsg()."</p>";
  360. return $s;
  361. }
  362. /*
  363. This script identifies the longest running SQL
  364. */
  365. function _SuspiciousSQL($numsql = 10)
  366. {
  367. global $ADODB_FETCH_MODE;
  368. $perf_table = adodb_perf::table();
  369. $saveE = $this->conn->fnExecute;
  370. $this->conn->fnExecute = false;
  371. if (isset($_GET['exps']) && isset($_GET['sql'])) {
  372. $partial = !empty($_GET['part']);
  373. echo "<a name=explain></a>".$this->Explain($_GET['sql'],$partial)."\n";
  374. }
  375. if (isset($_GET['sql'])) return;
  376. $sql1 = $this->sql1;
  377. $save = $ADODB_FETCH_MODE;
  378. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  379. if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
  380. //$this->conn->debug=1;
  381. $rs = $this->conn->SelectLimit(
  382. "select avg(timer) as avg_timer,$sql1,count(*),max(timer) as max_timer,min(timer) as min_timer
  383. from $perf_table
  384. where {$this->conn->upperCase}({$this->conn->substr}(sql0,1,5)) not in ('DROP ','INSER','COMMI','CREAT')
  385. and (tracer is null or tracer not like 'ERROR:%')
  386. group by sql1
  387. order by 1 desc",$numsql);
  388. if (isset($savem)) $this->conn->SetFetchMode($savem);
  389. $ADODB_FETCH_MODE = $save;
  390. $this->conn->fnExecute = $saveE;
  391. if (!$rs) return "<p>$this->helpurl. ".$this->conn->ErrorMsg()."</p>";
  392. $s = "<h3>Suspicious SQL</h3>
  393. <font size=1>The following SQL have high average execution times</font><br>
  394. <table border=1 bgcolor=white><tr><td><b>Avg Time</b><td><b>Count</b><td><b>SQL</b><td><b>Max</b><td><b>Min</b></tr>\n";
  395. $max = $this->maxLength;
  396. while (!$rs->EOF) {
  397. $sql = $rs->fields[1];
  398. $raw = urlencode($sql);
  399. if (strlen($raw)>$max-100) {
  400. $sql2 = substr($sql,0,$max-500);
  401. $raw = urlencode($sql2).'&part='.crc32($sql);
  402. }
  403. $prefix = "<a target=sql".rand()." href=\"?hidem=1&exps=1&sql=".$raw."&x#explain\">";
  404. $suffix = "</a>";
  405. if ($this->explain == false || strlen($prefix)>$max) {
  406. $suffix = ' ... <i>String too long for GET parameter: '.strlen($prefix).'</i>';
  407. $prefix = '';
  408. }
  409. $s .= "<tr><td>".adodb_round($rs->fields[0],6)."<td align=right>".$rs->fields[2]."<td><font size=-1>".$prefix.htmlspecialchars($sql).$suffix."</font>".
  410. "<td>".$rs->fields[3]."<td>".$rs->fields[4]."</tr>";
  411. $rs->MoveNext();
  412. }
  413. return $s."</table>";
  414. }
  415. function CheckMemory()
  416. {
  417. return '';
  418. }
  419. function SuspiciousSQL($numsql=10)
  420. {
  421. return adodb_perf::_SuspiciousSQL($numsql);
  422. }
  423. function ExpensiveSQL($numsql=10)
  424. {
  425. return adodb_perf::_ExpensiveSQL($numsql);
  426. }
  427. /*
  428. This reports the percentage of load on the instance due to the most
  429. expensive few SQL statements. Tuning these statements can often
  430. make huge improvements in overall system performance.
  431. */
  432. function _ExpensiveSQL($numsql = 10)
  433. {
  434. global $ADODB_FETCH_MODE;
  435. $perf_table = adodb_perf::table();
  436. $saveE = $this->conn->fnExecute;
  437. $this->conn->fnExecute = false;
  438. if (isset($_GET['expe']) && isset($_GET['sql'])) {
  439. $partial = !empty($_GET['part']);
  440. echo "<a name=explain></a>".$this->Explain($_GET['sql'],$partial)."\n";
  441. }
  442. if (isset($_GET['sql'])) return;
  443. $sql1 = $this->sql1;
  444. $save = $ADODB_FETCH_MODE;
  445. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  446. if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
  447. $rs = $this->conn->SelectLimit(
  448. "select sum(timer) as total,$sql1,count(*),max(timer) as max_timer,min(timer) as min_timer
  449. from $perf_table
  450. where {$this->conn->upperCase}({$this->conn->substr}(sql0,1,5)) not in ('DROP ','INSER','COMMI','CREAT')
  451. and (tracer is null or tracer not like 'ERROR:%')
  452. group by sql1
  453. having count(*)>1
  454. order by 1 desc",$numsql);
  455. if (isset($savem)) $this->conn->SetFetchMode($savem);
  456. $this->conn->fnExecute = $saveE;
  457. $ADODB_FETCH_MODE = $save;
  458. if (!$rs) return "<p>$this->helpurl. ".$this->conn->ErrorMsg()."</p>";
  459. $s = "<h3>Expensive SQL</h3>
  460. <font size=1>Tuning the following SQL could reduce the server load substantially</font><br>
  461. <table border=1 bgcolor=white><tr><td><b>Load</b><td><b>Count</b><td><b>SQL</b><td><b>Max</b><td><b>Min</b></tr>\n";
  462. $max = $this->maxLength;
  463. while (!$rs->EOF) {
  464. $sql = $rs->fields[1];
  465. $raw = urlencode($sql);
  466. if (strlen($raw)>$max-100) {
  467. $sql2 = substr($sql,0,$max-500);
  468. $raw = urlencode($sql2).'&part='.crc32($sql);
  469. }
  470. $prefix = "<a target=sqle".rand()." href=\"?hidem=1&expe=1&sql=".$raw."&x#explain\">";
  471. $suffix = "</a>";
  472. if($this->explain == false || strlen($prefix>$max)) {
  473. $prefix = '';
  474. $suffix = '';
  475. }
  476. $s .= "<tr><td>".adodb_round($rs->fields[0],6)."<td align=right>".$rs->fields[2]."<td><font size=-1>".$prefix.htmlspecialchars($sql).$suffix."</font>".
  477. "<td>".$rs->fields[3]."<td>".$rs->fields[4]."</tr>";
  478. $rs->MoveNext();
  479. }
  480. return $s."</table>";
  481. }
  482. /*
  483. Raw function to return parameter value from $settings.
  484. */
  485. function DBParameter($param)
  486. {
  487. if (empty($this->settings[$param])) return false;
  488. $sql = $this->settings[$param][1];
  489. return $this->_DBParameter($sql);
  490. }
  491. /*
  492. Raw function returning array of poll paramters
  493. */
  494. function PollParameters()
  495. {
  496. $arr[0] = (float)$this->DBParameter('data cache hit ratio');
  497. $arr[1] = (float)$this->DBParameter('data reads');
  498. $arr[2] = (float)$this->DBParameter('data writes');
  499. $arr[3] = (integer) $this->DBParameter('current connections');
  500. return $arr;
  501. }
  502. /*
  503. Low-level Get Database Parameter
  504. */
  505. function _DBParameter($sql)
  506. {
  507. $savelog = $this->conn->LogSQL(false);
  508. if (is_array($sql)) {
  509. global $ADODB_FETCH_MODE;
  510. $sql1 = $sql[0];
  511. $key = $sql[1];
  512. if (sizeof($sql)>2) $pos = $sql[2];
  513. else $pos = 1;
  514. if (sizeof($sql)>3) $coef = $sql[3];
  515. else $coef = false;
  516. $ret = false;
  517. $save = $ADODB_FETCH_MODE;
  518. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  519. if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
  520. $rs = $this->conn->Execute($sql1);
  521. if (isset($savem)) $this->conn->SetFetchMode($savem);
  522. $ADODB_FETCH_MODE = $save;
  523. if ($rs) {
  524. while (!$rs->EOF) {
  525. $keyf = reset($rs->fields);
  526. if (trim($keyf) == $key) {
  527. $ret = $rs->fields[$pos];
  528. if ($coef) $ret *= $coef;
  529. break;
  530. }
  531. $rs->MoveNext();
  532. }
  533. $rs->Close();
  534. }
  535. $this->conn->LogSQL($savelog);
  536. return $ret;
  537. } else {
  538. if (strncmp($sql,'=',1) == 0) {
  539. $fn = substr($sql,1);
  540. return $this->$fn();
  541. }
  542. $sql = str_replace('$DATABASE',$this->conn->database,$sql);
  543. $ret = $this->conn->GetOne($sql);
  544. $this->conn->LogSQL($savelog);
  545. return $ret;
  546. }
  547. }
  548. /*
  549. Warn if cache ratio falls below threshold. Displayed in "Description" column.
  550. */
  551. function WarnCacheRatio($val)
  552. {
  553. if ($val < $this->warnRatio)
  554. return '<font color=red><b>Cache ratio should be at least '.$this->warnRatio.'%</b></font>';
  555. else return '';
  556. }
  557. function clearsql()
  558. {
  559. $perf_table = adodb_perf::table();
  560. $this->conn->Execute("delete from $perf_table where created<".$this->conn->sysTimeStamp);
  561. }
  562. /***********************************************************************************************/
  563. // HIGH LEVEL UI FUNCTIONS
  564. /***********************************************************************************************/
  565. function UI($pollsecs=5)
  566. {
  567. global $ADODB_LOG_CONN;
  568. $perf_table = adodb_perf::table();
  569. $conn = $this->conn;
  570. $app = $conn->host;
  571. if ($conn->host && $conn->database) $app .= ', db=';
  572. $app .= $conn->database;
  573. if ($app) $app .= ', ';
  574. $savelog = $this->conn->LogSQL(false);
  575. $info = $conn->ServerInfo();
  576. if (isset($_GET['clearsql'])) {
  577. $this->clearsql();
  578. }
  579. $this->conn->LogSQL($savelog);
  580. // magic quotes
  581. if (isset($_GET['sql']) && get_magic_quotes_gpc()) {
  582. $_GET['sql'] = $_GET['sql'] = str_replace(array("\\'",'\"'),array("'",'"'),$_GET['sql']);
  583. }
  584. if (!isset($_SESSION['ADODB_PERF_SQL'])) $nsql = $_SESSION['ADODB_PERF_SQL'] = 10;
  585. else $nsql = $_SESSION['ADODB_PERF_SQL'];
  586. $app .= $info['description'];
  587. if (isset($_GET['do'])) $do = $_GET['do'];
  588. else if (isset($_POST['do'])) $do = $_POST['do'];
  589. else if (isset($_GET['sql'])) $do = 'viewsql';
  590. else $do = 'stats';
  591. if (isset($_GET['nsql'])) {
  592. if ($_GET['nsql'] > 0) $nsql = $_SESSION['ADODB_PERF_SQL'] = (integer) $_GET['nsql'];
  593. }
  594. echo "<title>ADOdb Performance Monitor on $app</title><body bgcolor=white>";
  595. if ($do == 'viewsql') $form = "<td><form># SQL:<input type=hidden value=viewsql name=do> <input type=text size=4 name=nsql value=$nsql><input type=submit value=Go></td></form>";
  596. else $form = "<td>&nbsp;</td>";
  597. $allowsql = !defined('ADODB_PERF_NO_RUN_SQL');
  598. global $ADODB_PERF_MIN;
  599. $app .= " (Min sql timing \$ADODB_PERF_MIN=$ADODB_PERF_MIN secs)";
  600. if (empty($_GET['hidem']))
  601. echo "<table border=1 width=100% bgcolor=lightyellow><tr><td colspan=2>
  602. <b><a href=http://adodb.sourceforge.net/?perf=1>ADOdb</a> Performance Monitor</b> <font size=1>for $app</font></tr><tr><td>
  603. <a href=?do=stats><b>Performance Stats</b></a> &nbsp; <a href=?do=viewsql><b>View SQL</b></a>
  604. &nbsp; <a href=?do=tables><b>View Tables</b></a> &nbsp; <a href=?do=poll><b>Poll Stats</b></a>",
  605. $allowsql ? ' &nbsp; <a href=?do=dosql><b>Run SQL</b></a>' : '',
  606. "$form",
  607. "</tr></table>";
  608. switch ($do) {
  609. default:
  610. case 'stats':
  611. if (empty($ADODB_LOG_CONN))
  612. echo "<p>&nbsp; <a href=\"?do=viewsql&clearsql=1\">Clear SQL Log</a><br>";
  613. echo $this->HealthCheck();
  614. //$this->conn->debug=1;
  615. echo $this->CheckMemory();
  616. break;
  617. case 'poll':
  618. echo "<iframe width=720 height=80%
  619. src=\"{$_SERVER['PHP_SELF']}?do=poll2&hidem=1\"></iframe>";
  620. break;
  621. case 'poll2':
  622. echo "<pre>";
  623. $this->Poll($pollsecs);
  624. break;
  625. case 'dosql':
  626. if (!$allowsql) break;
  627. $this->DoSQLForm();
  628. break;
  629. case 'viewsql':
  630. if (empty($_GET['hidem']))
  631. echo "&nbsp; <a href=\"?do=viewsql&clearsql=1\">Clear SQL Log</a><br>";
  632. echo($this->SuspiciousSQL($nsql));
  633. echo($this->ExpensiveSQL($nsql));
  634. echo($this->InvalidSQL($nsql));
  635. break;
  636. case 'tables':
  637. echo $this->Tables(); break;
  638. }
  639. global $ADODB_vers;
  640. echo "<p><div align=center><font size=1>$ADODB_vers Sponsored by <a href=http://phplens.com/>phpLens</a></font></div>";
  641. }
  642. /*
  643. Runs in infinite loop, returning real-time statistics
  644. */
  645. function Poll($secs=5)
  646. {
  647. $this->conn->fnExecute = false;
  648. //$this->conn->debug=1;
  649. if ($secs <= 1) $secs = 1;
  650. echo "Accumulating statistics, every $secs seconds...\n";flush();
  651. $arro = $this->PollParameters();
  652. $cnt = 0;
  653. set_time_limit(0);
  654. sleep($secs);
  655. while (1) {
  656. $arr = $this->PollParameters();
  657. $hits = sprintf('%2.2f',$arr[0]);
  658. $reads = sprintf('%12.4f',($arr[1]-$arro[1])/$secs);
  659. $writes = sprintf('%12.4f',($arr[2]-$arro[2])/$secs);
  660. $sess = sprintf('%5d',$arr[3]);
  661. $load = $this->CPULoad();
  662. if ($load !== false) {
  663. $oslabel = 'WS-CPU%';
  664. $osval = sprintf(" %2.1f ",(float) $load);
  665. }else {
  666. $oslabel = '';
  667. $osval = '';
  668. }
  669. if ($cnt % 10 == 0) echo " Time ".$oslabel." Hit% Sess Reads/s Writes/s\n";
  670. $cnt += 1;
  671. echo date('H:i:s').' '.$osval."$hits $sess $reads $writes\n";
  672. flush();
  673. if (connection_aborted()) return;
  674. sleep($secs);
  675. $arro = $arr;
  676. }
  677. }
  678. /*
  679. Returns basic health check in a command line interface
  680. */
  681. function HealthCheckCLI()
  682. {
  683. return $this->HealthCheck(true);
  684. }
  685. /*
  686. Returns basic health check as HTML
  687. */
  688. function HealthCheck($cli=false)
  689. {
  690. $saveE = $this->conn->fnExecute;
  691. $this->conn->fnExecute = false;
  692. if ($cli) $html = '';
  693. else $html = $this->table.'<tr><td colspan=3><h3>'.$this->conn->databaseType.'</h3></td></tr>'.$this->titles;
  694. $oldc = false;
  695. $bgc = '';
  696. foreach($this->settings as $name => $arr) {
  697. if ($arr === false) break;
  698. if (!is_string($name)) {
  699. if ($cli) $html .= " -- $arr -- \n";
  700. else $html .= "<tr bgcolor=$this->color><td colspan=3><i>$arr</i> &nbsp;</td></tr>";
  701. continue;
  702. }
  703. if (!is_array($arr)) break;
  704. $category = $arr[0];
  705. $how = $arr[1];
  706. if (sizeof($arr)>2) $desc = $arr[2];
  707. else $desc = ' &nbsp; ';
  708. if ($category == 'HIDE') continue;
  709. $val = $this->_DBParameter($how);
  710. if ($desc && strncmp($desc,"=",1) === 0) {
  711. $fn = substr($desc,1);
  712. $desc = $this->$fn($val);
  713. }
  714. if ($val === false) {
  715. $m = $this->conn->ErrorMsg();
  716. $val = "Error: $m";
  717. } else {
  718. if (is_numeric($val) && $val >= 256*1024) {
  719. if ($val % (1024*1024) == 0) {
  720. $val /= (1024*1024);
  721. $val .= 'M';
  722. } else if ($val % 1024 == 0) {
  723. $val /= 1024;
  724. $val .= 'K';
  725. }
  726. //$val = htmlspecialchars($val);
  727. }
  728. }
  729. if ($category != $oldc) {
  730. $oldc = $category;
  731. //$bgc = ($bgc == ' bgcolor='.$this->color) ? ' bgcolor=white' : ' bgcolor='.$this->color;
  732. }
  733. if (strlen($desc)==0) $desc = '&nbsp;';
  734. if (strlen($val)==0) $val = '&nbsp;';
  735. if ($cli) {
  736. $html .= str_replace('&nbsp;','',sprintf($this->cliFormat,strip_tags($name),strip_tags($val),strip_tags($desc)));
  737. }else {
  738. $html .= "<tr$bgc><td>".$name.'</td><td>'.$val.'</td><td>'.$desc."</td></tr>\n";
  739. }
  740. }
  741. if (!$cli) $html .= "</table>\n";
  742. $this->conn->fnExecute = $saveE;
  743. return $html;
  744. }
  745. function Tables($orderby='1')
  746. {
  747. if (!$this->tablesSQL) return false;
  748. $savelog = $this->conn->LogSQL(false);
  749. $rs = $this->conn->Execute($this->tablesSQL.' order by '.$orderby);
  750. $this->conn->LogSQL($savelog);
  751. $html = rs2html($rs,false,false,false,false);
  752. return $html;
  753. }
  754. function CreateLogTable()
  755. {
  756. if (!$this->createTableSQL) return false;
  757. $table = $this->table();
  758. $sql = str_replace('adodb_logsql',$table,$this->createTableSQL);
  759. $savelog = $this->conn->LogSQL(false);
  760. $ok = $this->conn->Execute($sql);
  761. $this->conn->LogSQL($savelog);
  762. return ($ok) ? true : false;
  763. }
  764. function DoSQLForm()
  765. {
  766. $PHP_SELF = $_SERVER['PHP_SELF'];
  767. $sql = isset($_REQUEST['sql']) ? $_REQUEST['sql'] : '';
  768. if (isset($_SESSION['phplens_sqlrows'])) $rows = $_SESSION['phplens_sqlrows'];
  769. else $rows = 3;
  770. if (isset($_REQUEST['SMALLER'])) {
  771. $rows /= 2;
  772. if ($rows < 3) $rows = 3;
  773. $_SESSION['phplens_sqlrows'] = $rows;
  774. }
  775. if (isset($_REQUEST['BIGGER'])) {
  776. $rows *= 2;
  777. $_SESSION['phplens_sqlrows'] = $rows;
  778. }
  779. ?>
  780. <form method="POST" action="<?php echo $PHP_SELF ?>">
  781. <table><tr>
  782. <td> Form size: <input type="submit" value=" &lt; " name="SMALLER"><input type="submit" value=" &gt; &gt; " name="BIGGER">
  783. </td>
  784. <td align=right>
  785. <input type="submit" value=" Run SQL Below " name="RUN"><input type=hidden name=do value=dosql>
  786. </td></tr>
  787. <tr>
  788. <td colspan=2><textarea rows=<?php print $rows; ?> name="sql" cols="80"><?php print htmlspecialchars($sql) ?></textarea>
  789. </td>
  790. </tr>
  791. </table>
  792. </form>
  793. <?php
  794. if (!isset($_REQUEST['sql'])) return;
  795. $sql = $this->undomq(trim($sql));
  796. if (substr($sql,strlen($sql)-1) === ';') {
  797. $print = true;
  798. $sqla = $this->SplitSQL($sql);
  799. } else {
  800. $print = false;
  801. $sqla = array($sql);
  802. }
  803. foreach($sqla as $sqls) {
  804. if (!$sqls) continue;
  805. if ($print) {
  806. print "<p>".htmlspecialchars($sqls)."</p>";
  807. flush();
  808. }
  809. $savelog = $this->conn->LogSQL(false);
  810. $rs = $this->conn->Execute($sqls);
  811. $this->conn->LogSQL($savelog);
  812. if ($rs && is_object($rs) && !$rs->EOF) {
  813. rs2html($rs);
  814. while ($rs->NextRecordSet()) {
  815. print "<table width=98% bgcolor=#C0C0FF><tr><td>&nbsp;</td></tr></table>";
  816. rs2html($rs);
  817. }
  818. } else {
  819. $e1 = (integer) $this->conn->ErrorNo();
  820. $e2 = $this->conn->ErrorMsg();
  821. if (($e1) || ($e2)) {
  822. if (empty($e1)) $e1 = '-1'; // postgresql fix
  823. print ' &nbsp; '.$e1.': '.$e2;
  824. } else {
  825. print "<p>No Recordset returned<br></p>";
  826. }
  827. }
  828. } // foreach
  829. }
  830. function SplitSQL($sql)
  831. {
  832. $arr = explode(';',$sql);
  833. return $arr;
  834. }
  835. function undomq($m)
  836. {
  837. if (get_magic_quotes_gpc()) {
  838. // undo the damage
  839. $m = str_replace('\\\\','\\',$m);
  840. $m = str_replace('\"','"',$m);
  841. $m = str_replace('\\\'','\'',$m);
  842. }
  843. return $m;
  844. }
  845. /************************************************************************/
  846. /**
  847. * Reorganise multiple table-indices/statistics/..
  848. * OptimizeMode could be given by last Parameter
  849. *
  850. * @example
  851. * <pre>
  852. * optimizeTables( 'tableA');
  853. * </pre>
  854. * <pre>
  855. * optimizeTables( 'tableA', 'tableB', 'tableC');
  856. * </pre>
  857. * <pre>
  858. * optimizeTables( 'tableA', 'tableB', ADODB_OPT_LOW);
  859. * </pre>
  860. *
  861. * @param string table name of the table to optimize
  862. * @param int mode optimization-mode
  863. * <code>ADODB_OPT_HIGH</code> for full optimization
  864. * <code>ADODB_OPT_LOW</code> for CPU-less optimization
  865. * Default is LOW <code>ADODB_OPT_LOW</code>
  866. * @author Markus Staab
  867. * @return Returns <code>true</code> on success and <code>false</code> on error
  868. */
  869. function OptimizeTables()
  870. {
  871. $args = func_get_args();
  872. $numArgs = func_num_args();
  873. if ( $numArgs == 0) return false;
  874. $mode = ADODB_OPT_LOW;
  875. $lastArg = $args[ $numArgs - 1];
  876. if ( !is_string($lastArg)) {
  877. $mode = $lastArg;
  878. unset( $args[ $numArgs - 1]);
  879. }
  880. foreach( $args as $table) {
  881. $this->optimizeTable( $table, $mode);
  882. }
  883. }
  884. /**
  885. * Reorganise the table-indices/statistics/.. depending on the given mode.
  886. * Default Implementation throws an error.
  887. *
  888. * @param string table name of the table to optimize
  889. * @param int mode optimization-mode
  890. * <code>ADODB_OPT_HIGH</code> for full optimization
  891. * <code>ADODB_OPT_LOW</code> for CPU-less optimization
  892. * Default is LOW <code>ADODB_OPT_LOW</code>
  893. * @author Markus Staab
  894. * @return Returns <code>true</code> on success and <code>false</code> on error
  895. */
  896. function OptimizeTable( $table, $mode = ADODB_OPT_LOW)
  897. {
  898. ADOConnection::outp( sprintf( "<p>%s: '%s' not implemented for driver '%s'</p>", __CLASS__, __FUNCTION__, $this->conn->databaseType));
  899. return false;
  900. }
  901. /**
  902. * Reorganise current database.
  903. * Default implementation loops over all <code>MetaTables()</code> and
  904. * optimize each using <code>optmizeTable()</code>
  905. *
  906. * @author Markus Staab
  907. * @return Returns <code>true</code> on success and <code>false</code> on error
  908. */
  909. function optimizeDatabase()
  910. {
  911. $conn = $this->conn;
  912. if ( !$conn) return false;
  913. $tables = $conn->MetaTables( 'TABLES');
  914. if ( !$tables ) return false;
  915. foreach( $tables as $table) {
  916. if ( !$this->optimizeTable( $table)) {
  917. return false;
  918. }
  919. }
  920. return true;
  921. }
  922. // end hack
  923. }
  924. ?>