PageRenderTime 65ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 1ms

/libraries/adodb.493a/adodb-perf.inc.php

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