adodb-perf.inc.php 31 KB

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