PageRenderTime 50ms CodeModel.GetById 11ms RepoModel.GetById 1ms app.codeStats 0ms

/05_Desarrollo/lib/adodb/adodb-perf.inc.php

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