PageRenderTime 60ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/concrete/libraries/3rdparty/adodb/adodb-perf.inc.php

https://bitbucket.org/selfeky/xclusivescardwebsite
PHP | 1099 lines | 888 code | 96 blank | 115 comment | 132 complexity | a0479ec8862e08d0716da923f4751a19 MD5 | raw file
  1. <?php
  2. /*
  3. V5.18 3 Sep 2012 (c) 2000-2012 John Lim (jlim#natsoft.com). 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. /* obsolete: return microtime value as a float. Retained for backward compat */
  44. function adodb_microtime()
  45. {
  46. return microtime(true);
  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. $a0 = microtime(true);
  54. $rs = $connx->Execute($sql,$inputarr);
  55. $a1 = microtime(true);
  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. $time = $a1 - $a0;
  71. if (!$rs) {
  72. $errM = $connx->ErrorMsg();
  73. $errN = $connx->ErrorNo();
  74. $conn->lastInsID = 0;
  75. $tracer = substr('ERROR: '.htmlspecialchars($errM),0,250);
  76. } else {
  77. $tracer = '';
  78. $errM = '';
  79. $errN = 0;
  80. $dbg = $conn->debug;
  81. $conn->debug = false;
  82. if (!is_object($rs) || $rs->dataProvider == 'empty')
  83. $conn->_affected = $conn->affected_rows(true);
  84. $conn->lastInsID = @$conn->Insert_ID();
  85. $conn->debug = $dbg;
  86. }
  87. if (isset($_SERVER['HTTP_HOST'])) {
  88. $tracer .= '<br>'.$_SERVER['HTTP_HOST'];
  89. if (isset($_SERVER['PHP_SELF'])) $tracer .= htmlspecialchars($_SERVER['PHP_SELF']);
  90. } else
  91. if (isset($_SERVER['PHP_SELF'])) $tracer .= '<br>'.htmlspecialchars($_SERVER['PHP_SELF']);
  92. //$tracer .= (string) adodb_backtrace(false);
  93. $tracer = (string) substr($tracer,0,500);
  94. if (is_array($inputarr)) {
  95. if (is_array(reset($inputarr))) $params = 'Array sizeof='.sizeof($inputarr);
  96. else {
  97. // Quote string parameters so we can see them in the
  98. // performance stats. This helps spot disabled indexes.
  99. $xar_params = $inputarr;
  100. foreach ($xar_params as $xar_param_key => $xar_param) {
  101. if (gettype($xar_param) == 'string')
  102. $xar_params[$xar_param_key] = '"' . $xar_param . '"';
  103. }
  104. $params = implode(', ', $xar_params);
  105. if (strlen($params) >= 3000) $params = substr($params, 0, 3000);
  106. }
  107. } else {
  108. $params = '';
  109. }
  110. if (is_array($sql)) $sql = $sql[0];
  111. if ($prefix) $sql = $prefix.$sql;
  112. $arr = array('b'=>strlen($sql).'.'.crc32($sql),
  113. 'c'=>substr($sql,0,3900), 'd'=>$params,'e'=>$tracer,'f'=>adodb_round($time,6));
  114. //var_dump($arr);
  115. $saved = $conn->debug;
  116. $conn->debug = 0;
  117. $d = $conn->sysTimeStamp;
  118. if (empty($d)) $d = date("'Y-m-d H:i:s'");
  119. if ($conn->dataProvider == 'oci8' && $dbT != 'oci8po') {
  120. $isql = "insert into $perf_table values($d,:b,:c,:d,:e,:f)";
  121. } else if ($dbT == 'odbc_mssql' || $dbT == 'informix' || strncmp($dbT,'odbtp',4)==0) {
  122. $timer = $arr['f'];
  123. if ($dbT == 'informix') $sql2 = substr($sql2,0,230);
  124. $sql1 = $conn->qstr($arr['b']);
  125. $sql2 = $conn->qstr($arr['c']);
  126. $params = $conn->qstr($arr['d']);
  127. $tracer = $conn->qstr($arr['e']);
  128. $isql = "insert into $perf_table (created,sql0,sql1,params,tracer,timer) values($d,$sql1,$sql2,$params,$tracer,$timer)";
  129. if ($dbT == 'informix') $isql = str_replace(chr(10),' ',$isql);
  130. $arr = false;
  131. } else {
  132. if ($dbT == 'db2') $arr['f'] = (float) $arr['f'];
  133. $isql = "insert into $perf_table (created,sql0,sql1,params,tracer,timer) values( $d,?,?,?,?,?)";
  134. }
  135. global $ADODB_PERF_MIN;
  136. if ($errN != 0 || $time >= $ADODB_PERF_MIN) {
  137. $ok = $conn->Execute($isql,$arr);
  138. } else
  139. $ok = true;
  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. static 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://social.technet.microsoft.com/Forums/en-US/winservergen/thread/414b0e1b-499c-411e-8a02-6a12e339c0f1/
  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. static $FAIL = false;
  225. if ($FAIL) return false;
  226. $objName = "winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\CIMV2";
  227. $myQuery = "SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor WHERE Name = '_Total'";
  228. try {
  229. @$objWMIService = new COM($objName);
  230. if (!$objWMIService) {
  231. $FAIL = true;
  232. return false;
  233. }
  234. $info[0] = -1;
  235. $info[1] = 0;
  236. $info[2] = 0;
  237. $info[3] = 0;
  238. foreach($objWMIService->ExecQuery($myQuery) as $objItem) {
  239. $info[0] = $objItem->PercentProcessorTime();
  240. }
  241. } catch(Exception $e) {
  242. $FAIL = true;
  243. echo $e->getMessage();
  244. return false;
  245. }
  246. return $info;
  247. }
  248. // Algorithm - Steve Blinch (BlitzAffe Online, http://www.blitzaffe.com)
  249. $statfile = '/proc/stat';
  250. if (!file_exists($statfile)) return false;
  251. $fd = fopen($statfile,"r");
  252. if (!$fd) return false;
  253. $statinfo = explode("\n",fgets($fd, 1024));
  254. fclose($fd);
  255. foreach($statinfo as $line) {
  256. $info = explode(" ",$line);
  257. if($info[0]=="cpu") {
  258. array_shift($info); // pop off "cpu"
  259. if(!$info[0]) array_shift($info); // pop off blank space (if any)
  260. return $info;
  261. }
  262. }
  263. return false;
  264. }
  265. /* NOT IMPLEMENTED */
  266. function MemInfo()
  267. {
  268. /*
  269. total: used: free: shared: buffers: cached:
  270. Mem: 1055289344 917299200 137990144 0 165437440 599773184
  271. Swap: 2146775040 11055104 2135719936
  272. MemTotal: 1030556 kB
  273. MemFree: 134756 kB
  274. MemShared: 0 kB
  275. Buffers: 161560 kB
  276. Cached: 581384 kB
  277. SwapCached: 4332 kB
  278. Active: 494468 kB
  279. Inact_dirty: 322856 kB
  280. Inact_clean: 24256 kB
  281. Inact_target: 168316 kB
  282. HighTotal: 131064 kB
  283. HighFree: 1024 kB
  284. LowTotal: 899492 kB
  285. LowFree: 133732 kB
  286. SwapTotal: 2096460 kB
  287. SwapFree: 2085664 kB
  288. Committed_AS: 348732 kB
  289. */
  290. }
  291. /*
  292. Remember that this is client load, not db server load!
  293. */
  294. var $_lastLoad;
  295. function CPULoad()
  296. {
  297. $info = $this->_CPULoad();
  298. if (!$info) return false;
  299. if (strncmp(PHP_OS,'WIN',3)==0) {
  300. return (integer) $info[0];
  301. }else {
  302. if (empty($this->_lastLoad)) {
  303. sleep(1);
  304. $this->_lastLoad = $info;
  305. $info = $this->_CPULoad();
  306. }
  307. $last = $this->_lastLoad;
  308. $this->_lastLoad = $info;
  309. $d_user = $info[0] - $last[0];
  310. $d_nice = $info[1] - $last[1];
  311. $d_system = $info[2] - $last[2];
  312. $d_idle = $info[3] - $last[3];
  313. //printf("Delta - User: %f Nice: %f System: %f Idle: %f<br>",$d_user,$d_nice,$d_system,$d_idle);
  314. $total=$d_user+$d_nice+$d_system+$d_idle;
  315. if ($total<1) $total=1;
  316. return 100*($d_user+$d_nice+$d_system)/$total;
  317. }
  318. }
  319. function Tracer($sql)
  320. {
  321. $perf_table = adodb_perf::table();
  322. $saveE = $this->conn->fnExecute;
  323. $this->conn->fnExecute = false;
  324. global $ADODB_FETCH_MODE;
  325. $save = $ADODB_FETCH_MODE;
  326. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  327. if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
  328. $sqlq = $this->conn->qstr($sql);
  329. $arr = $this->conn->GetArray(
  330. "select count(*),tracer
  331. from $perf_table where sql1=$sqlq
  332. group by tracer
  333. order by 1 desc");
  334. $s = '';
  335. if ($arr) {
  336. $s .= '<h3>Scripts Affected</h3>';
  337. foreach($arr as $k) {
  338. $s .= sprintf("%4d",$k[0]).' &nbsp; '.strip_tags($k[1]).'<br>';
  339. }
  340. }
  341. if (isset($savem)) $this->conn->SetFetchMode($savem);
  342. $ADODB_CACHE_MODE = $save;
  343. $this->conn->fnExecute = $saveE;
  344. return $s;
  345. }
  346. /*
  347. Explain Plan for $sql.
  348. If only a snippet of the $sql is passed in, then $partial will hold the crc32 of the
  349. actual sql.
  350. */
  351. function Explain($sql,$partial=false)
  352. {
  353. return false;
  354. }
  355. function InvalidSQL($numsql = 10)
  356. {
  357. if (isset($_GET['sql'])) return;
  358. $s = '<h3>Invalid SQL</h3>';
  359. $saveE = $this->conn->fnExecute;
  360. $this->conn->fnExecute = false;
  361. $perf_table = adodb_perf::table();
  362. $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);
  363. $this->conn->fnExecute = $saveE;
  364. if ($rs) {
  365. $s .= rs2html($rs,false,false,false,false);
  366. } else
  367. return "<p>$this->helpurl. ".$this->conn->ErrorMsg()."</p>";
  368. return $s;
  369. }
  370. /*
  371. This script identifies the longest running SQL
  372. */
  373. function _SuspiciousSQL($numsql = 10)
  374. {
  375. global $ADODB_FETCH_MODE;
  376. $perf_table = adodb_perf::table();
  377. $saveE = $this->conn->fnExecute;
  378. $this->conn->fnExecute = false;
  379. if (isset($_GET['exps']) && isset($_GET['sql'])) {
  380. $partial = !empty($_GET['part']);
  381. echo "<a name=explain></a>".$this->Explain($_GET['sql'],$partial)."\n";
  382. }
  383. if (isset($_GET['sql'])) return;
  384. $sql1 = $this->sql1;
  385. $save = $ADODB_FETCH_MODE;
  386. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  387. if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
  388. //$this->conn->debug=1;
  389. $rs = $this->conn->SelectLimit(
  390. "select avg(timer) as avg_timer,$sql1,count(*),max(timer) as max_timer,min(timer) as min_timer
  391. from $perf_table
  392. where {$this->conn->upperCase}({$this->conn->substr}(sql0,1,5)) not in ('DROP ','INSER','COMMI','CREAT')
  393. and (tracer is null or tracer not like 'ERROR:%')
  394. group by sql1
  395. order by 1 desc",$numsql);
  396. if (isset($savem)) $this->conn->SetFetchMode($savem);
  397. $ADODB_FETCH_MODE = $save;
  398. $this->conn->fnExecute = $saveE;
  399. if (!$rs) return "<p>$this->helpurl. ".$this->conn->ErrorMsg()."</p>";
  400. $s = "<h3>Suspicious SQL</h3>
  401. <font size=1>The following SQL have high average execution times</font><br>
  402. <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";
  403. $max = $this->maxLength;
  404. while (!$rs->EOF) {
  405. $sql = $rs->fields[1];
  406. $raw = urlencode($sql);
  407. if (strlen($raw)>$max-100) {
  408. $sql2 = substr($sql,0,$max-500);
  409. $raw = urlencode($sql2).'&part='.crc32($sql);
  410. }
  411. $prefix = "<a target=sql".rand()." href=\"?hidem=1&exps=1&sql=".$raw."&x#explain\">";
  412. $suffix = "</a>";
  413. if ($this->explain == false || strlen($prefix)>$max) {
  414. $suffix = ' ... <i>String too long for GET parameter: '.strlen($prefix).'</i>';
  415. $prefix = '';
  416. }
  417. $s .= "<tr><td>".adodb_round($rs->fields[0],6)."<td align=right>".$rs->fields[2]."<td><font size=-1>".$prefix.htmlspecialchars($sql).$suffix."</font>".
  418. "<td>".$rs->fields[3]."<td>".$rs->fields[4]."</tr>";
  419. $rs->MoveNext();
  420. }
  421. return $s."</table>";
  422. }
  423. function CheckMemory()
  424. {
  425. return '';
  426. }
  427. function SuspiciousSQL($numsql=10)
  428. {
  429. return adodb_perf::_SuspiciousSQL($numsql);
  430. }
  431. function ExpensiveSQL($numsql=10)
  432. {
  433. return adodb_perf::_ExpensiveSQL($numsql);
  434. }
  435. /*
  436. This reports the percentage of load on the instance due to the most
  437. expensive few SQL statements. Tuning these statements can often
  438. make huge improvements in overall system performance.
  439. */
  440. function _ExpensiveSQL($numsql = 10)
  441. {
  442. global $ADODB_FETCH_MODE;
  443. $perf_table = adodb_perf::table();
  444. $saveE = $this->conn->fnExecute;
  445. $this->conn->fnExecute = false;
  446. if (isset($_GET['expe']) && isset($_GET['sql'])) {
  447. $partial = !empty($_GET['part']);
  448. echo "<a name=explain></a>".$this->Explain($_GET['sql'],$partial)."\n";
  449. }
  450. if (isset($_GET['sql'])) return;
  451. $sql1 = $this->sql1;
  452. $save = $ADODB_FETCH_MODE;
  453. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  454. if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
  455. $rs = $this->conn->SelectLimit(
  456. "select sum(timer) as total,$sql1,count(*),max(timer) as max_timer,min(timer) as min_timer
  457. from $perf_table
  458. where {$this->conn->upperCase}({$this->conn->substr}(sql0,1,5)) not in ('DROP ','INSER','COMMI','CREAT')
  459. and (tracer is null or tracer not like 'ERROR:%')
  460. group by sql1
  461. having count(*)>1
  462. order by 1 desc",$numsql);
  463. if (isset($savem)) $this->conn->SetFetchMode($savem);
  464. $this->conn->fnExecute = $saveE;
  465. $ADODB_FETCH_MODE = $save;
  466. if (!$rs) return "<p>$this->helpurl. ".$this->conn->ErrorMsg()."</p>";
  467. $s = "<h3>Expensive SQL</h3>
  468. <font size=1>Tuning the following SQL could reduce the server load substantially</font><br>
  469. <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";
  470. $max = $this->maxLength;
  471. while (!$rs->EOF) {
  472. $sql = $rs->fields[1];
  473. $raw = urlencode($sql);
  474. if (strlen($raw)>$max-100) {
  475. $sql2 = substr($sql,0,$max-500);
  476. $raw = urlencode($sql2).'&part='.crc32($sql);
  477. }
  478. $prefix = "<a target=sqle".rand()." href=\"?hidem=1&expe=1&sql=".$raw."&x#explain\">";
  479. $suffix = "</a>";
  480. if($this->explain == false || strlen($prefix>$max)) {
  481. $prefix = '';
  482. $suffix = '';
  483. }
  484. $s .= "<tr><td>".adodb_round($rs->fields[0],6)."<td align=right>".$rs->fields[2]."<td><font size=-1>".$prefix.htmlspecialchars($sql).$suffix."</font>".
  485. "<td>".$rs->fields[3]."<td>".$rs->fields[4]."</tr>";
  486. $rs->MoveNext();
  487. }
  488. return $s."</table>";
  489. }
  490. /*
  491. Raw function to return parameter value from $settings.
  492. */
  493. function DBParameter($param)
  494. {
  495. if (empty($this->settings[$param])) return false;
  496. $sql = $this->settings[$param][1];
  497. return $this->_DBParameter($sql);
  498. }
  499. /*
  500. Raw function returning array of poll paramters
  501. */
  502. function PollParameters()
  503. {
  504. $arr[0] = (float)$this->DBParameter('data cache hit ratio');
  505. $arr[1] = (float)$this->DBParameter('data reads');
  506. $arr[2] = (float)$this->DBParameter('data writes');
  507. $arr[3] = (integer) $this->DBParameter('current connections');
  508. return $arr;
  509. }
  510. /*
  511. Low-level Get Database Parameter
  512. */
  513. function _DBParameter($sql)
  514. {
  515. $savelog = $this->conn->LogSQL(false);
  516. if (is_array($sql)) {
  517. global $ADODB_FETCH_MODE;
  518. $sql1 = $sql[0];
  519. $key = $sql[1];
  520. if (sizeof($sql)>2) $pos = $sql[2];
  521. else $pos = 1;
  522. if (sizeof($sql)>3) $coef = $sql[3];
  523. else $coef = false;
  524. $ret = false;
  525. $save = $ADODB_FETCH_MODE;
  526. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  527. if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
  528. $rs = $this->conn->Execute($sql1);
  529. if (isset($savem)) $this->conn->SetFetchMode($savem);
  530. $ADODB_FETCH_MODE = $save;
  531. if ($rs) {
  532. while (!$rs->EOF) {
  533. $keyf = reset($rs->fields);
  534. if (trim($keyf) == $key) {
  535. $ret = $rs->fields[$pos];
  536. if ($coef) $ret *= $coef;
  537. break;
  538. }
  539. $rs->MoveNext();
  540. }
  541. $rs->Close();
  542. }
  543. $this->conn->LogSQL($savelog);
  544. return $ret;
  545. } else {
  546. if (strncmp($sql,'=',1) == 0) {
  547. $fn = substr($sql,1);
  548. return $this->$fn();
  549. }
  550. $sql = str_replace('$DATABASE',$this->conn->database,$sql);
  551. $ret = $this->conn->GetOne($sql);
  552. $this->conn->LogSQL($savelog);
  553. return $ret;
  554. }
  555. }
  556. /*
  557. Warn if cache ratio falls below threshold. Displayed in "Description" column.
  558. */
  559. function WarnCacheRatio($val)
  560. {
  561. if ($val < $this->warnRatio)
  562. return '<font color=red><b>Cache ratio should be at least '.$this->warnRatio.'%</b></font>';
  563. else return '';
  564. }
  565. function clearsql()
  566. {
  567. $perf_table = adodb_perf::table();
  568. $this->conn->Execute("delete from $perf_table where created<".$this->conn->sysTimeStamp);
  569. }
  570. /***********************************************************************************************/
  571. // HIGH LEVEL UI FUNCTIONS
  572. /***********************************************************************************************/
  573. function UI($pollsecs=5)
  574. {
  575. global $ADODB_LOG_CONN;
  576. $perf_table = adodb_perf::table();
  577. $conn = $this->conn;
  578. $app = $conn->host;
  579. if ($conn->host && $conn->database) $app .= ', db=';
  580. $app .= $conn->database;
  581. if ($app) $app .= ', ';
  582. $savelog = $this->conn->LogSQL(false);
  583. $info = $conn->ServerInfo();
  584. if (isset($_GET['clearsql'])) {
  585. $this->clearsql();
  586. }
  587. $this->conn->LogSQL($savelog);
  588. // magic quotes
  589. if (isset($_GET['sql']) && get_magic_quotes_gpc()) {
  590. $_GET['sql'] = $_GET['sql'] = str_replace(array("\\'",'\"'),array("'",'"'),$_GET['sql']);
  591. }
  592. if (!isset($_SESSION['ADODB_PERF_SQL'])) $nsql = $_SESSION['ADODB_PERF_SQL'] = 10;
  593. else $nsql = $_SESSION['ADODB_PERF_SQL'];
  594. $app .= $info['description'];
  595. if (isset($_GET['do'])) $do = $_GET['do'];
  596. else if (isset($_POST['do'])) $do = $_POST['do'];
  597. else if (isset($_GET['sql'])) $do = 'viewsql';
  598. else $do = 'stats';
  599. if (isset($_GET['nsql'])) {
  600. if ($_GET['nsql'] > 0) $nsql = $_SESSION['ADODB_PERF_SQL'] = (integer) $_GET['nsql'];
  601. }
  602. echo "<title>ADOdb Performance Monitor on $app</title><body bgcolor=white>";
  603. 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>";
  604. else $form = "<td>&nbsp;</td>";
  605. $allowsql = !defined('ADODB_PERF_NO_RUN_SQL');
  606. global $ADODB_PERF_MIN;
  607. $app .= " (Min sql timing \$ADODB_PERF_MIN=$ADODB_PERF_MIN secs)";
  608. if (empty($_GET['hidem']))
  609. echo "<table border=1 width=100% bgcolor=lightyellow><tr><td colspan=2>
  610. <b><a href=http://adodb.sourceforge.net/?perf=1>ADOdb</a> Performance Monitor</b> <font size=1>for $app</font></tr><tr><td>
  611. <a href=?do=stats><b>Performance Stats</b></a> &nbsp; <a href=?do=viewsql><b>View SQL</b></a>
  612. &nbsp; <a href=?do=tables><b>View Tables</b></a> &nbsp; <a href=?do=poll><b>Poll Stats</b></a>",
  613. $allowsql ? ' &nbsp; <a href=?do=dosql><b>Run SQL</b></a>' : '',
  614. "$form",
  615. "</tr></table>";
  616. switch ($do) {
  617. default:
  618. case 'stats':
  619. if (empty($ADODB_LOG_CONN))
  620. echo "<p>&nbsp; <a href=\"?do=viewsql&clearsql=1\">Clear SQL Log</a><br>";
  621. echo $this->HealthCheck();
  622. //$this->conn->debug=1;
  623. echo $this->CheckMemory();
  624. break;
  625. case 'poll':
  626. $self = htmlspecialchars($_SERVER['PHP_SELF']);
  627. echo "<iframe width=720 height=80%
  628. src=\"{$self}?do=poll2&hidem=1\"></iframe>";
  629. break;
  630. case 'poll2':
  631. echo "<pre>";
  632. $this->Poll($pollsecs);
  633. break;
  634. case 'dosql':
  635. if (!$allowsql) break;
  636. $this->DoSQLForm();
  637. break;
  638. case 'viewsql':
  639. if (empty($_GET['hidem']))
  640. echo "&nbsp; <a href=\"?do=viewsql&clearsql=1\">Clear SQL Log</a><br>";
  641. echo($this->SuspiciousSQL($nsql));
  642. echo($this->ExpensiveSQL($nsql));
  643. echo($this->InvalidSQL($nsql));
  644. break;
  645. case 'tables':
  646. echo $this->Tables(); break;
  647. }
  648. global $ADODB_vers;
  649. echo "<p><div align=center><font size=1>$ADODB_vers Sponsored by <a href=http://phplens.com/>phpLens</a></font></div>";
  650. }
  651. /*
  652. Runs in infinite loop, returning real-time statistics
  653. */
  654. function Poll($secs=5)
  655. {
  656. $this->conn->fnExecute = false;
  657. //$this->conn->debug=1;
  658. if ($secs <= 1) $secs = 1;
  659. echo "Accumulating statistics, every $secs seconds...\n";flush();
  660. $arro = $this->PollParameters();
  661. $cnt = 0;
  662. set_time_limit(0);
  663. sleep($secs);
  664. while (1) {
  665. $arr = $this->PollParameters();
  666. $hits = sprintf('%2.2f',$arr[0]);
  667. $reads = sprintf('%12.4f',($arr[1]-$arro[1])/$secs);
  668. $writes = sprintf('%12.4f',($arr[2]-$arro[2])/$secs);
  669. $sess = sprintf('%5d',$arr[3]);
  670. $load = $this->CPULoad();
  671. if ($load !== false) {
  672. $oslabel = 'WS-CPU%';
  673. $osval = sprintf(" %2.1f ",(float) $load);
  674. }else {
  675. $oslabel = '';
  676. $osval = '';
  677. }
  678. if ($cnt % 10 == 0) echo " Time ".$oslabel." Hit% Sess Reads/s Writes/s\n";
  679. $cnt += 1;
  680. echo date('H:i:s').' '.$osval."$hits $sess $reads $writes\n";
  681. flush();
  682. if (connection_aborted()) return;
  683. sleep($secs);
  684. $arro = $arr;
  685. }
  686. }
  687. /*
  688. Returns basic health check in a command line interface
  689. */
  690. function HealthCheckCLI()
  691. {
  692. return $this->HealthCheck(true);
  693. }
  694. /*
  695. Returns basic health check as HTML
  696. */
  697. function HealthCheck($cli=false)
  698. {
  699. $saveE = $this->conn->fnExecute;
  700. $this->conn->fnExecute = false;
  701. if ($cli) $html = '';
  702. else $html = $this->table.'<tr><td colspan=3><h3>'.$this->conn->databaseType.'</h3></td></tr>'.$this->titles;
  703. $oldc = false;
  704. $bgc = '';
  705. foreach($this->settings as $name => $arr) {
  706. if ($arr === false) break;
  707. if (!is_string($name)) {
  708. if ($cli) $html .= " -- $arr -- \n";
  709. else $html .= "<tr bgcolor=$this->color><td colspan=3><i>$arr</i> &nbsp;</td></tr>";
  710. continue;
  711. }
  712. if (!is_array($arr)) break;
  713. $category = $arr[0];
  714. $how = $arr[1];
  715. if (sizeof($arr)>2) $desc = $arr[2];
  716. else $desc = ' &nbsp; ';
  717. if ($category == 'HIDE') continue;
  718. $val = $this->_DBParameter($how);
  719. if ($desc && strncmp($desc,"=",1) === 0) {
  720. $fn = substr($desc,1);
  721. $desc = $this->$fn($val);
  722. }
  723. if ($val === false) {
  724. $m = $this->conn->ErrorMsg();
  725. $val = "Error: $m";
  726. } else {
  727. if (is_numeric($val) && $val >= 256*1024) {
  728. if ($val % (1024*1024) == 0) {
  729. $val /= (1024*1024);
  730. $val .= 'M';
  731. } else if ($val % 1024 == 0) {
  732. $val /= 1024;
  733. $val .= 'K';
  734. }
  735. //$val = htmlspecialchars($val);
  736. }
  737. }
  738. if ($category != $oldc) {
  739. $oldc = $category;
  740. //$bgc = ($bgc == ' bgcolor='.$this->color) ? ' bgcolor=white' : ' bgcolor='.$this->color;
  741. }
  742. if (strlen($desc)==0) $desc = '&nbsp;';
  743. if (strlen($val)==0) $val = '&nbsp;';
  744. if ($cli) {
  745. $html .= str_replace('&nbsp;','',sprintf($this->cliFormat,strip_tags($name),strip_tags($val),strip_tags($desc)));
  746. }else {
  747. $html .= "<tr$bgc><td>".$name.'</td><td>'.$val.'</td><td>'.$desc."</td></tr>\n";
  748. }
  749. }
  750. if (!$cli) $html .= "</table>\n";
  751. $this->conn->fnExecute = $saveE;
  752. return $html;
  753. }
  754. function Tables($orderby='1')
  755. {
  756. if (!$this->tablesSQL) return false;
  757. $savelog = $this->conn->LogSQL(false);
  758. $rs = $this->conn->Execute($this->tablesSQL.' order by '.$orderby);
  759. $this->conn->LogSQL($savelog);
  760. $html = rs2html($rs,false,false,false,false);
  761. return $html;
  762. }
  763. function CreateLogTable()
  764. {
  765. if (!$this->createTableSQL) return false;
  766. $table = $this->table();
  767. $sql = str_replace('adodb_logsql',$table,$this->createTableSQL);
  768. $savelog = $this->conn->LogSQL(false);
  769. $ok = $this->conn->Execute($sql);
  770. $this->conn->LogSQL($savelog);
  771. return ($ok) ? true : false;
  772. }
  773. function DoSQLForm()
  774. {
  775. $PHP_SELF = htmlspecialchars($_SERVER['PHP_SELF']);
  776. $sql = isset($_REQUEST['sql']) ? $_REQUEST['sql'] : '';
  777. if (isset($_SESSION['phplens_sqlrows'])) $rows = $_SESSION['phplens_sqlrows'];
  778. else $rows = 3;
  779. if (isset($_REQUEST['SMALLER'])) {
  780. $rows /= 2;
  781. if ($rows < 3) $rows = 3;
  782. $_SESSION['phplens_sqlrows'] = $rows;
  783. }
  784. if (isset($_REQUEST['BIGGER'])) {
  785. $rows *= 2;
  786. $_SESSION['phplens_sqlrows'] = $rows;
  787. }
  788. ?>
  789. <form method="POST" action="<?php echo $PHP_SELF ?>">
  790. <table><tr>
  791. <td> Form size: <input type="submit" value=" &lt; " name="SMALLER"><input type="submit" value=" &gt; &gt; " name="BIGGER">
  792. </td>
  793. <td align=right>
  794. <input type="submit" value=" Run SQL Below " name="RUN"><input type=hidden name=do value=dosql>
  795. </td></tr>
  796. <tr>
  797. <td colspan=2><textarea rows=<?php print $rows; ?> name="sql" cols="80"><?php print htmlspecialchars($sql) ?></textarea>
  798. </td>
  799. </tr>
  800. </table>
  801. </form>
  802. <?php
  803. if (!isset($_REQUEST['sql'])) return;
  804. $sql = $this->undomq(trim($sql));
  805. if (substr($sql,strlen($sql)-1) === ';') {
  806. $print = true;
  807. $sqla = $this->SplitSQL($sql);
  808. } else {
  809. $print = false;
  810. $sqla = array($sql);
  811. }
  812. foreach($sqla as $sqls) {
  813. if (!$sqls) continue;
  814. if ($print) {
  815. print "<p>".htmlspecialchars($sqls)."</p>";
  816. flush();
  817. }
  818. $savelog = $this->conn->LogSQL(false);
  819. $rs = $this->conn->Execute($sqls);
  820. $this->conn->LogSQL($savelog);
  821. if ($rs && is_object($rs) && !$rs->EOF) {
  822. rs2html($rs);
  823. while ($rs->NextRecordSet()) {
  824. print "<table width=98% bgcolor=#C0C0FF><tr><td>&nbsp;</td></tr></table>";
  825. rs2html($rs);
  826. }
  827. } else {
  828. $e1 = (integer) $this->conn->ErrorNo();
  829. $e2 = $this->conn->ErrorMsg();
  830. if (($e1) || ($e2)) {
  831. if (empty($e1)) $e1 = '-1'; // postgresql fix
  832. print ' &nbsp; '.$e1.': '.$e2;
  833. } else {
  834. print "<p>No Recordset returned<br></p>";
  835. }
  836. }
  837. } // foreach
  838. }
  839. function SplitSQL($sql)
  840. {
  841. $arr = explode(';',$sql);
  842. return $arr;
  843. }
  844. function undomq($m)
  845. {
  846. if (get_magic_quotes_gpc()) {
  847. // undo the damage
  848. $m = str_replace('\\\\','\\',$m);
  849. $m = str_replace('\"','"',$m);
  850. $m = str_replace('\\\'','\'',$m);
  851. }
  852. return $m;
  853. }
  854. /************************************************************************/
  855. /**
  856. * Reorganise multiple table-indices/statistics/..
  857. * OptimizeMode could be given by last Parameter
  858. *
  859. * @example
  860. * <pre>
  861. * optimizeTables( 'tableA');
  862. * </pre>
  863. * <pre>
  864. * optimizeTables( 'tableA', 'tableB', 'tableC');
  865. * </pre>
  866. * <pre>
  867. * optimizeTables( 'tableA', 'tableB', ADODB_OPT_LOW);
  868. * </pre>
  869. *
  870. * @param string table name of the table to optimize
  871. * @param int mode optimization-mode
  872. * <code>ADODB_OPT_HIGH</code> for full optimization
  873. * <code>ADODB_OPT_LOW</code> for CPU-less optimization
  874. * Default is LOW <code>ADODB_OPT_LOW</code>
  875. * @author Markus Staab
  876. * @return Returns <code>true</code> on success and <code>false</code> on error
  877. */
  878. function OptimizeTables()
  879. {
  880. $args = func_get_args();
  881. $numArgs = func_num_args();
  882. if ( $numArgs == 0) return false;
  883. $mode = ADODB_OPT_LOW;
  884. $lastArg = $args[ $numArgs - 1];
  885. if ( !is_string($lastArg)) {
  886. $mode = $lastArg;
  887. unset( $args[ $numArgs - 1]);
  888. }
  889. foreach( $args as $table) {
  890. $this->optimizeTable( $table, $mode);
  891. }
  892. }
  893. /**
  894. * Reorganise the table-indices/statistics/.. depending on the given mode.
  895. * Default Implementation throws an error.
  896. *
  897. * @param string table name of the table to optimize
  898. * @param int mode optimization-mode
  899. * <code>ADODB_OPT_HIGH</code> for full optimization
  900. * <code>ADODB_OPT_LOW</code> for CPU-less optimization
  901. * Default is LOW <code>ADODB_OPT_LOW</code>
  902. * @author Markus Staab
  903. * @return Returns <code>true</code> on success and <code>false</code> on error
  904. */
  905. function OptimizeTable( $table, $mode = ADODB_OPT_LOW)
  906. {
  907. ADOConnection::outp( sprintf( "<p>%s: '%s' not implemented for driver '%s'</p>", __CLASS__, __FUNCTION__, $this->conn->databaseType));
  908. return false;
  909. }
  910. /**
  911. * Reorganise current database.
  912. * Default implementation loops over all <code>MetaTables()</code> and
  913. * optimize each using <code>optmizeTable()</code>
  914. *
  915. * @author Markus Staab
  916. * @return Returns <code>true</code> on success and <code>false</code> on error
  917. */
  918. function optimizeDatabase()
  919. {
  920. $conn = $this->conn;
  921. if ( !$conn) return false;
  922. $tables = $conn->MetaTables( 'TABLES');
  923. if ( !$tables ) return false;
  924. foreach( $tables as $table) {
  925. if ( !$this->optimizeTable( $table)) {
  926. return false;
  927. }
  928. }
  929. return true;
  930. }
  931. // end hack
  932. }
  933. ?>