adodb-perf.inc.php 31 KB

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