<?php
####################################################
# Author: Ivan　谭俊青　
# email:drinching@gmail.com
# QQ:55300231
# msn:showsa@live.cn
# copyright: GPL v3.0
# date: 2008-01-14
####################################################

error_reporting(E_ERROR);

#####################################################
# 配置
#####################################################
$config = array(
	'host' 		=> '192.168.7.250',
	'username' 	=> 'search',
	'password' 	=> 'xxxxxxxxxxxxx',
	'dbname' 	=> 'test',
	'port' 		=> 3306
);
#####################################################







header( 'Content-type:text/html; charset=utf-8' );
header( 'Expires: Mon, 08 Aug 2005 08:00:00 GMT' ); // Date in the past
header( 'Cache-Control: no-cache, no-store, must-revalidate, private, max-age=0', false );         // HTTP/1.1
header( 'Pragma: no-cache' );



$ip = mysql_escape_string(trim($_REQUEST['ip']));



if($ip)
{
	/*
	$matches = array();
	if(preg_match('#^(\d+).(\d+).(\d+).(\d+)$#', $ip, $matches))
	{
		################
	}
	else 
	{
		echo '请正确输入IP地址：10.10.*.*';
		exit;
	}
	*/

	$mysqli_monitor = new mysqli(
		$config['host'],
		$config['username'], 
		$config['password'],
		$config['dbname'],
		$config['port']
	);
	
	/* check connection */
	if (mysqli_connect_errno())
	{	
		printf("Connect failed: %s\n", mysqli_connect_error() . ' on ' . $config['host'] . ':' . $config['port']);
		echo 'in ', __FILE__, ' on line ', __LINE__;
		exit();
	}
	

	# 根据ip地址从dbinfo里面取得有关信息
	$sql = 'select * from DbInfo.t_all_info where f_ip=' . "'$ip'";
	$result = $mysqli_monitor->query($sql);
	if ($result)
	{
		$row = $result->fetch_array(MYSQLI_BOTH);
		if (!$row['f_port'])
		{
			$row['f_port'] = 3306;
		}
	}
	else 
	{
		echo '请检查IP是否正确';
		exit;
	}
	
	
	# 检验是否有对应的 master or slave ip, 如果没有则退出 并提示
	/*
	if (empty($row['f_ms_ip']))
	{
		echo '请检查t_all_info表中是否存在对应的master or slave...';
		exit;
	}
	else 
	{
		$ms_ip = $row['f_ms_ip'];
	}
	
	# 检查到有对应的 m/s ip
	if ($row['f_role_type'] == 'master')
	{
		$ip_role_type = 'master';
		$ms_ip_role_type = 'slave';
	}
	else 
	{
		$ip_role_type = 'slave';
		$ms_ip_role_type = 'master';
	}
	*/

	$config['host'] = $row['f_ip'];
	$config['port'] = $row['f_port'];
	$config['dbname'] = ''; # 有些可能不存在test库，因此留空
	
	$mysqli = new mysqli(
		$config['host'],
		$config['username'], 
		$config['password'],
		$config['dbname'],
		$config['port']
	);
	
	/* check connection */
	if (mysqli_connect_errno())
	{	
		printf("Connect failed: %s\n", mysqli_connect_error());
		echo 'in ', __FILE__, ' on line ', __LINE__;
		exit();
	}
	
	$sql = 'show processlist';
	$result = $mysqli->query($sql);
	$has_slave  = false;
	while ($tmp_row = mysqli_fetch_assoc($result))
	{
		# print_r($tmp_row);
		# 如果有 Command 列有 Binlog Dump，则表示有slave
		if (preg_match('#binlog.*#is', $tmp_row['Command']))
		{
			$has_slave = true;
			$slave_host_port_arr = explode(':', $tmp_row['Host']);
			$slave_ip = $slave_host_port_arr[0];

			$sql = 'select * from DbInfo.t_all_info where f_ms_ip=\''. $row['f_ip'] .'\' and f_ip=' . "'$slave_ip'";
			$result = $mysqli_monitor->query($sql);
			$slave_row = $result->fetch_array(MYSQLI_BOTH);
			$slave_row['f_port'] = $slave_row['f_port'] ? $slave_row['f_port'] : 3306 ;
		}		
	}

	$sql = 'show slave status';
	$result = $mysqli->query($sql);
	$has_master = false;
	if ($result)
	{
		$tmp_row = $result->fetch_array(MYSQLI_ASSOC);
		#print_r($tmp_row);
		if ($tmp_row)
		{
			$has_master = true;
			$master_ip = $tmp_row['Master_Host'];
			$master_port = $tmp_row['Master_Port'];
			
			$sql = 'select * from DbInfo.t_all_info where f_ip=' . "'$master_ip'";
			$result = $mysqli_monitor->query($sql);
			$master_row = $result->fetch_array(MYSQLI_BOTH);
		}
	}

}
?>




<html>

<!-- 

####################################################
# Author: Ivan　谭俊青　
# email:drinching@gmail.com
# QQ:55300231
# msn:showsa@live.cn
# date: 2008-01-15
####################################################

-->

	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

		
		<style media="screen" type="text/css">
		#loading-mask{position:absolute;left:0;top:0;width:100%;height:100%;z-index:20000;background-color:white;}
		#loading{position:absolute;left:45%;top:40%;padding:2px;z-index:20001;height:auto;}
		#loading a {color:#225588;}
		#loading .loading-indicator{background:white;color:#444;font:bold 13pt tahoma,arial,helvetica;padding:10px;margin:0;height:auto;}
		#loading-msg {font: normal 9pt arial,tahoma,sans-serif;}
		.record_sep
		{
			width:'100%';
			font-size:1px;
			line-height:1px;
			background-color:#c3daf9;
			marin:0 0 0 0;
			padding:0 0 0 0;
		}

		</style>
		<link href="/scripts/ext-2.2/resources/css/ext-all.css" media="screen" rel="stylesheet" type="text/css" >
		<link href="/styles/dboa.css?200812261656" media="screen" rel="stylesheet" type="text/css" >
	</head>
	
	<body>
	
		<div id="loading-mask"></div> 
		<div id="loading"> 
			<div class="loading-indicator">
				<div class="loading-indicator">
					<img src="/scripts/ext-2.2/resources/images/default/shared/large-loading.gif" style="margin-right:8px;float:left;vertical-align:top;"/>
					DBOA
					<br />
					<span id="loading-msg">加载中...</span>
				</div>
			</div> 
		</div> 
		
		<script type="text/javascript" src="/scripts/ext-2.2/adapter/ext/ext-base.js"></script>
		<script type="text/javascript" src="/scripts/ext-2.2/ext-all.js"></script>
		<script type="text/javascript" src="/scripts/ext-2.2/build/locale/ext-lang-zh_CN.js"></script>
		<script type="text/javascript">
			Ext.BLANK_IMAGE_URL = '/scripts/ext-2.2/resources/images/default/s.gif';  // Ext 2.0 +
			
			function explode(seperator, string)
			{
			    return string.split(seperator);
			}
			
			Math.randomMax = function(maxVal,asFloat){
				var val = Math.random()*maxVal;
				return asFloat?val:Math.round(val);
			}
			
			var current_record_loading = false;
			var slave_record_loading = false;
			var master_record_loading = false;
			
			Ext.onReady(function(){
			
				function treeClick(node,e)
				{
				
					if(node.isLeaf())
					{
						Ext.getCmp('db_tree').disable();
						
						e.stopEvent();
						
						node_arr = explode('__ivan__', node.id);
						
						// current
						setTimeout("update_db_table_record_no('current-records', '<?php echo $row['f_ip'];?>', '<?php echo $row['f_port'];?>', '" + node_arr[0] + "', '" + node_arr[1] + "')", 200);
						current_record_loading = true;
						
						// slave
						<?php if ($has_slave) {?>
						setTimeout("update_db_table_record_no('slave-records', '<?php echo $slave_ip;?>', '<?php echo $slave_row['f_port'];?>', '" + node_arr[0] + "', '" + node_arr[1] + "')", 200);
						slave_record_loading = true;
						<?php } ?>
						
						// master
						<?php if ($has_master) { ?>
						setTimeout("update_db_table_record_no('master-records', '<?php echo $master_ip;?>', '<?php echo $master_row['f_port'];?>', '" + node_arr[0] + "', '" + node_arr[1] + "')", 200);
						master_record_loading = true;
						<?php } ?>
						
						
						
					}
				}
			
			
			    // shorthand
			    var Tree = Ext.tree;
			    
			    var tree = new Tree.TreePanel({
			        el:'tree-div',
			        id:'db_tree',
			        useArrows:true,
			        autoScroll:true,
			        animate:true,
			        enableDD:true,
			        containerScroll: true,
			
			        // auto create TreeLoader
			        dataUrl: 'getDBTableTreeNodes.php?ip=<?php echo $has_master ? $master_ip : $row['f_ip'];?>&port=<?php echo $has_master ? $master_port : $row['f_port'];?>',
			
			        root: {
			            nodeType: 'async',
			            text: '数据库列表',
			            draggable:false,
			            id:'__root'
			        }
			    });
			    // render the tree
			    tree.render();
			    tree.getRootNode().expand();
			    
			    tree.on('click',treeClick);
			});


		</script>


		<div id="contentDiv" style="width:100%;">
		
		
			<form action="" id="check_ms_record_num" style="margin:10px;padding:10px;">

				请输入上海Master IP: <input name="ip" id="ip" type="text" value="<?php echo $ip;?>" />
				<input type="submit" name="submit" value="submit">
			
			</form>
			
			<div style="margin:10px;padding:10px;">
			
			<?php
			if($ip)
			{
				echo 
					'<table style="margin:0px;padding:0px;">';
				echo 
					'<tr><td colspan="5"><div class="record_sep">&nbsp;</td></td></tr>';
				echo 
					'<tr>',
						'<td width="80"></td>',
						'<td width="160">IP:port</td>',
						'<td width="160">主机名</td>',
						'<td width="180">分类</td>',
						'<td width="180">描述</td>',
					'</tr>';
				echo 
					'<tr><td colspan="5"><div class="record_sep">&nbsp;</td></td></tr>';
				
				if ($has_master)
				{
					echo 
					'<tr>',
						'<td>Master</td>',
						'<td>', $master_ip, ':', $master_port, '</td>',
						'<td>', $master_row['f_host'],'</td>',
						'<td>', iconv('gb2312', 'utf-8', $master_row['f_class']),'</td>',
						'<td>', iconv('gb2312', 'utf-8', $master_row['f_desc']),'</td>',
					'</tr>';
				}
				
				echo 
					'<tr>',
						'<td>Current</td>',
						'<td>', $row['f_ip'], ':', $row['f_port'] ? $row['f_port'] : 3306, '</td>',
						'<td>', $row['f_host'],'</td>',
						'<td>', iconv('gb2312', 'utf-8', $row['f_class']),'</td>',
						'<td>', iconv('gb2312', 'utf-8', $row['f_desc']),'</td>',
					'</tr>';
			
				if ($has_slave)
				{
					echo 
					'<tr>',
						'<td>Slave</td>',
						'<td>', $slave_ip, ':', $slave_row['f_port'], '</td>',
						'<td>', $slave_row['f_host'],'</td>',
						'<td>', iconv('gb2312', 'utf-8', $slave_row['f_class']),'</td>',
						'<td>', iconv('gb2312', 'utf-8', $slave_row['f_desc']),'</td>',
					'</tr>';
				}
				echo 
					'<tr><td colspan="5"><div class="record_sep">&nbsp;</td></td></tr>';
				
				echo '</table>';
			}
			?>
			
			</div>
					
					
					
					
			<div id="tree-div" style="float:left;overflow:auto; padding:0px;margin:10px;margin-left:20px;height:300px;width:270px;"></div> 
		
			<?php if($ip) { ?>
			<div id="record-display-div-current" style="overflow:auto;float:left;padding:10px;margin:10px;height:300px;width:250px;border:1px solid #c3daf9;">
			
				Current: <?php echo $row['f_ip']; ?> <a href="#" style="text-decoration:none;" onclick="javascript:{document.getElementById('current-records').innerHTML='';}">清空</a>
				<div class="record_sep">&nbsp;</div>
				
				<div id="current-records"></div>
				
			
			</div> 
			<?php } ?>
			
			
			<?php if ($has_master) { ?>
			<div id="record-display-div-master" style="overflow:auto;float:left;padding:10px;margin:10px;height:300px;width:250px;border:1px solid #c3daf9;">
			
				Master <?php echo $has_master? ': ' . $master_ip : ''; ?> <a href="#" style="text-decoration:none;" onclick="javascript:{document.getElementById('master-records').innerHTML='';}">清空</a>
				<div class="record_sep">&nbsp;</div>
				
				<div id="master-records"></div>
			
			</div> 
			<?php } ?>
			
			
			
			<?php if ($has_slave) { ?>
			<div id="record-display-div-slave" style="overflow:auto;float:left;padding:10px;margin:10px;height:300px;width:250px;border:1px solid #c3daf9;">
			
				Slave<?php echo $has_slave? ': ' . $slave_ip : ''; ?> <a href="#" style="text-decoration:none;" onclick="javascript:{document.getElementById('slave-records').innerHTML='';}">清空</a>
				<div class="record_sep">&nbsp;</div>
				
				<div id="slave-records"></div>
			
			</div> 
			<?php } ?>
			
			

			

		</div>



		<script type="text/javascript">
		
			function update_db_table_record_no( div_id, ip, port, db, table )
			{
				// div_id = current-reocrds, slave-reocrds ,master-reocrds
				current_records_div = document.getElementById('current-records');
				slave_records_div = document.getElementById('slave-records');
				master_records_div = document.getElementById('master-records');

				Ext.Ajax.request({
					disableCaching:true,
					url: 'fetchTableRecord.php?ip=' + ip + '&port=' + port + '&db=' + db + '&table=' + table,
					success: function(result, request) {
						var res = Ext.decode(result.responseText);
						
						if(div_id == 'current-records')
						{
							div_obj = current_records_div;
							current_record_loading = false;
							var scroll_body = document.getElementById('record-display-div-current');
						}
						else if(div_id == 'slave-records')
						{
							div_obj = slave_records_div;
							slave_record_loading = false;
							var scroll_body = document.getElementById('record-display-div-slave');
						}
						else if(div_id == 'master-records')
						{
							div_obj = master_records_div;
							master_record_loading = false;
							var scroll_body = document.getElementById('record-display-div-master');
						}
						
						var ivan_rand = Math.randomMax( 10000 )
						var tmp_str = '<span id="' + db + table + ivan_rand +'">' + db + '.' + table + ': ' + res.count + '</span>';
							
						if(res.success == false)
							var tmp_str = '<span id="' + db + table + ivan_rand +'">' + db + '.' + table + ': ' + '出错了...' + '</span>';
						
						div_obj.innerHTML = div_obj.innerHTML + tmp_str + '<br>';
						scroll_body.scrollTop = scroll_body.scrollHeight;

						Ext.fly(db+table+ivan_rand).pause(.2).highlight('#FF00FF', {attr:'color'});
						
						if(!(current_record_loading || slave_record_loading ||  master_record_loading))
						{
							Ext.getCmp('db_tree').enable();
						}
						if(res.success == false)
						{
							Ext.getCmp('db_tree').enable();
						}
					},
					failure: function(result, request) { 
						alert('网络超时(可能是记录数太大所致)... 请联系DB组');
						Ext.getCmp('db_tree').enable();
					},
					autoAbort:false
				});
			}

			Ext.EventManager.on(window, 'load', function(){
				setTimeout(function(){
					Ext.get('loading').remove();
					Ext.get('loading-mask').fadeOut({duration:.15, remove:true});
			    }, 250); 
			});
			
		</script>
		
		
	</body>

</html>





















