Sfoglia il codice sorgente

提交统计相关、

walkor 11 anni fa
parent
commit
143d6ec6ea

+ 1 - 0
applications/Statistics/Lib/Cache.php

@@ -1,4 +1,5 @@
 <?php
+namespace Statistics\Lib;
 class Cache
 {
     public static $statisticDataCache = array();

+ 2 - 2
applications/Statistics/Lib/functions.php

@@ -70,10 +70,10 @@ function multiRequest($request_buffer_array)
     foreach($read_buffer as $address => $buf)
     {
         list($ip, $port) = explode(':', $address);
-        Cache::$lastSuccessIpArray[$ip] = $ip;
+        \Statistics\Lib\Cache::$lastSuccessIpArray[$ip] = $ip;
     }
 
-    Cache::$lastFailedIpArray = array_diff($ip_list, Cache::$lastSuccessIpArray);
+     \Statistics\Lib\Cache::$lastFailedIpArray = array_diff($ip_list,  \Statistics\Lib\Cache::$lastSuccessIpArray);
 
     ksort($read_buffer);
 

+ 64 - 0
applications/Statistics/Modules/logger.php

@@ -0,0 +1,64 @@
+<?php
+namespace Statistics\Modules;
+function logger($module, $interface, $date, $start_time, $offset, $count)
+{
+        $module_str ='';
+        foreach(\Statistics\Lib\Cache::$modulesDataCache as $mod => $interfaces)
+        {
+                if($mod == 'WorkerMan')
+                {
+                    continue;
+                }
+                $module_str .= '<li><a href="/?fn=statistic&module='.$mod.'">'.$mod.'</a></li>';
+                if($module == $mod)
+                {
+                    foreach ($interfaces as $if)
+                    {
+                        $module_str .= '<li>&nbsp;&nbsp;<a href="/?fn=statistic&module='.$mod.'&interface='.$if.'">'.$if.'</a></li>';
+                    }
+                }
+        } 
+        
+        $log_data_arr = getStasticLog($module, $interface, $start_time ,$offset, $count);
+        unset($_GET['fn'], $_GET['ip'], $_GET['offset']);
+        $log_str = '';
+        foreach($log_data_arr as $address => $log_data)
+        {
+            list($ip, $port) = explode(':', $address);
+            $log_str .= $log_data['data'];
+            $_GET['ip'][] = $ip;
+            $_GET['offset'][] = $log_data['offset'];
+        }
+        
+        $next_page_url = http_build_query($_GET);
+        $log_str .= "</br><center><a href='/?fn=logger&$next_page_url'>下一页</a></center>";
+
+        include ST_ROOT . '/Views/header.tpl.php';
+        include ST_ROOT . '/Views/log.tpl.php';
+        include ST_ROOT . '/Views/footer.tpl.php';
+}
+
+function getStasticLog($module, $interface , $start_time, $offset = '', $count = 10)
+{
+    $ip_list = (!empty($_GET['ip']) && is_array($_GET['ip'])) ? $_GET['ip'] : \Statistics\Lib\Cache::$ServerIpList;
+    $offset_list = (!empty($_GET['offset']) && is_array($_GET['offset'])) ? $_GET['offset'] : array();
+    $port = 55858;
+    $request_buffer_array = array();
+    foreach($ip_list as $key=>$ip)
+    {
+        $offset = isset($offset_list[$key]) ? $offset_list[$key] : 0;
+        $request_buffer_array["$ip:$port"] = json_encode(array('cmd'=>'get_log', 'module'=>$module, 'interface'=>$interface, 'start_time'=>$start_time,  'offset'=>$offset, 'count'=>$count));
+    }
+
+    $read_buffer_array = multiRequest($request_buffer_array);
+    ksort($read_buffer_array);
+    foreach($read_buffer_array as $address => $buf)
+    {
+        list($ip, $port) = explode(':', $address);
+        $body_data = json_decode(trim($buf), true);
+        $log_data = isset($body_data['data']) ? $body_data['data'] : '';
+        $offset = isset($body_data['offset']) ? $body_data['offset'] : 0;
+        $read_buffer_array[$address] = array('offset'=>$offset,'data'=>$log_data);
+    }
+    return $read_buffer_array;
+}

+ 23 - 11
applications/Statistics/Modules/main.php

@@ -1,13 +1,16 @@
 <?php
-function main($module, $interface, $date, $offset)
+namespace Statistics\Modules;
+function main($module, $interface, $date, $start_time, $offset)
 {
     $module = 'WorkerMan';
     $interface = 'Statistics';
+    $today = date('Y-m-d');
+    $time_now = time();
     multiRequestStAndModules($module, $interface, $date);
     $all_st_str = '';
-    if(is_array(Cache::$statisticDataCache['statistic']))
+    if(is_array(\Statistics\Lib\Cache::$statisticDataCache['statistic']))
     {
-        foreach(Cache::$statisticDataCache['statistic'] as $ip=>$st_str)
+        foreach(\Statistics\Lib\Cache::$statisticDataCache['statistic'] as $ip=>$st_str)
         {
             $all_st_str .= $st_str;
         }
@@ -58,9 +61,18 @@ function main($module, $interface, $date, $offset)
         $code_pie_data = implode(',', $code_pie_array);
     }
     
-    unset($_GET['start_time'], $_GET['end_time'], $_GET['date']);
+    unset($_GET['start_time'], $_GET['end_time'], $_GET['date'], $_GET['fn']);
     $query = http_build_query($_GET);
     
+    // 删除末尾0的记录
+    if($today == $date)
+    {
+        while(!empty($data) && ($item = end($data)) && $item['total_count'] == 0 && ($key = key($data)) &&  $time_now < $key)
+        {
+            unset($data[$key]);
+        }
+    }
+    
     $table_data = '';
     if($data)
     {
@@ -98,7 +110,7 @@ function main($module, $interface, $date, $offset)
                         <td> {$item['total_avg_time']}</td>
                         <td>{$item['suc_count']}</td>
                         <td>{$item['suc_avg_time']}</td>
-                        <td>".($item['fail_count']>0?("<a href='/?fn=log&$query&start_time=".strtotime($item['time'])."&end_time=".(strtotime($item['time'])+300)."'>{$item['fail_count']}</a>"):$item['fail_count'])."</td>
+                        <td>".($item['fail_count']>0?("<a href='/?fn=logger&$query&start_time=".strtotime($item['time'])."&end_time=".(strtotime($item['time'])+300)."'>{$item['fail_count']}</a>"):$item['fail_count'])."</td>
                         <td>{$item['fail_avg_time']}</td>
                         <td>{$item['precent']}%</td>
                     </tr>
@@ -130,9 +142,9 @@ function main($module, $interface, $date, $offset)
 
 function multiRequestStAndModules($module, $interface, $date)
 {
-    Cache::$statisticDataCache['statistic'] = '';
+    \Statistics\Lib\Cache::$statisticDataCache['statistic'] = '';
     $buffer = json_encode(array('cmd'=>'get_statistic','module'=>$module, 'interface'=>$interface, 'date'=>$date))."\n";
-    $ip_list = (!empty($_GET['server_ip']) && is_array($_GET['server_ip'])) ? $_GET['server_ip'] : Cache::$ServerIpList;
+    $ip_list = (!empty($_GET['ip']) && is_array($_GET['ip'])) ? $_GET['ip'] : \Statistics\Lib\Cache::$ServerIpList;
     $reqest_buffer_array = array();
     $port =  55858;
     foreach($ip_list as $ip)
@@ -149,16 +161,16 @@ function multiRequestStAndModules($module, $interface, $date)
         // 整理modules
         foreach($modules_data as $mod => $interfaces)
         {
-            if(!isset(Cache::$modulesDataCache[$mod]))
+            if(!isset(\Statistics\Lib\Cache::$modulesDataCache[$mod]))
             {
-                Cache::$modulesDataCache[$mod] = array();
+                \Statistics\Lib\Cache::$modulesDataCache[$mod] = array();
             }
             foreach($interfaces as $if)
             {
-                Cache::$modulesDataCache[$mod][$if] = $if;
+                \Statistics\Lib\Cache::$modulesDataCache[$mod][$if] = $if;
             }
         }
-        Cache::$statisticDataCache['statistic'][$ip] = $statistic_data;
+        \Statistics\Lib\Cache::$statisticDataCache['statistic'][$ip] = $statistic_data;
     }
 }
 

+ 132 - 0
applications/Statistics/Modules/statistic.php

@@ -1,5 +1,137 @@
 <?php
+namespace Statistics\Modules;
 function statistic($module, $interface, $date, $start_time, $offset)
 {
     
+    $today = date('Y-m-d');
+    $time_now = time();
+    multiRequestStAndModules($module, $interface, $date);
+    $all_st_str = '';
+    if(is_array(\Statistics\Lib\Cache::$statisticDataCache['statistic']))
+    {
+        foreach(\Statistics\Lib\Cache::$statisticDataCache['statistic'] as $ip=>$st_str)
+        {
+            $all_st_str .= $st_str;
+        }
+    }
+
+    $code_map = array();
+    $data = formatSt($all_st_str, $date, $code_map);
+    $interface_name = "$module::$interface";
+    $success_series_data = $fail_series_data = $success_time_series_data = $fail_time_series_data = array();
+    $total_count = $fail_count = 0;
+    foreach($data as $time_point=>$item)
+    {
+        if($item['total_count'])
+        {
+            $success_series_data[] = "[".($time_point*1000).",{$item['total_count']}]";
+            $total_count += $item['total_count'];
+        }
+        $fail_series_data[] = "[".($time_point*1000).",{$item['fail_count']}]";
+        $fail_count += $item['fail_count'];
+        if($item['total_avg_time'])
+        {
+            $success_time_series_data[] = "[".($time_point*1000).",{$item['total_avg_time']}]";
+        }
+        $fail_time_series_data[] = "[".($time_point*1000).",{$item['fail_avg_time']}]";
+    }
+    $success_series_data = implode(',', $success_series_data);
+    $fail_series_data = implode(',', $fail_series_data);
+    $success_time_series_data = implode(',', $success_time_series_data);
+    $fail_time_series_data = implode(',', $fail_time_series_data);
+
+    unset($_GET['start_time'], $_GET['end_time'], $_GET['date'], $_GET['fn']);
+    $query = http_build_query($_GET);
+
+    // 删除末尾0的记录
+    if($today == $date)
+    {
+        while(!empty($data) && ($item = end($data)) && $item['total_count'] == 0 && ($key = key($data)) &&  $time_now < $key)
+        {
+            unset($data[$key]);
+        }
+    }
+
+    $table_data = '';
+    if($data)
+    {
+        $first_line = true;
+        foreach($data as $item)
+        {
+            if($first_line)
+            {
+                $first_line = false;
+                if($item['total_count'] == 0)
+                {
+                    continue;
+                }
+            }
+            $html_class = 'class="danger"';
+            if($item['total_count'] == 0)
+            {
+                $html_class = '';
+            }
+            elseif($item['precent']>=99.99)
+            {
+                $html_class = 'class="success"';
+            }
+            elseif($item['precent']>=99)
+            {
+                $html_class = '';
+            }
+            elseif($item['precent']>=98)
+            {
+                $html_class = 'class="warning"';
+            }
+            $table_data .= "\n<tr $html_class>
+            <td>{$item['time']}</td>
+            <td>{$item['total_count']}</td>
+            <td> {$item['total_avg_time']}</td>
+            <td>{$item['suc_count']}</td>
+            <td>{$item['suc_avg_time']}</td>
+            <td>".($item['fail_count']>0?("<a href='/?fn=logger&$query&start_time=".strtotime($item['time'])."&end_time=".(strtotime($item['time'])+300)."'>{$item['fail_count']}</a>"):$item['fail_count'])."</td>
+            <td>{$item['fail_avg_time']}</td>
+            <td>{$item['precent']}%</td>
+            </tr>
+            ";
+        }
+        }
+
+        // date btn
+        $date_btn_str = '';
+        for($i=13;$i>=1;$i--)
+        {
+        $the_time = strtotime("-$i day");
+        $the_date = date('Y-m-d',$the_time);
+        $html_the_date = $date == $the_date ? "<b>$the_date</b>" : $the_date;
+        $date_btn_str .= '<a href="/?date='."$the_date&$query".'" class="btn '.$html_class.'" type="button">'.$html_the_date.'</a>';
+        if($i == 7)
+        {
+            $date_btn_str .= '</br>';
+        }
+        }
+        $the_date = date('Y-m-d');
+        $html_the_date = $date == $the_date ? "<b>$the_date</b>" : $the_date;
+        $date_btn_str .=  '<a href="/?date='."$the_date&$query".'" class="btn" type="button">'.$html_the_date.'</a>';
+        
+        $module_str ='';
+        foreach(\Statistics\Lib\Cache::$modulesDataCache as $mod => $interfaces)
+        {
+                if($mod == 'WorkerMan')
+                {
+                    continue;
+                }
+                $module_str .= '<li><a href="/?fn=statistic&module='.$mod.'">'.$mod.'</a></li>';
+                if($module == $mod)
+                {
+                    foreach ($interfaces as $if)
+                    {
+                        $module_str .= '<li>&nbsp;&nbsp;<a href="/?fn=statistic&module='.$mod.'&interface='.$if.'">'.$if.'</a></li>';
+                    }
+                }
+        } 
+
+        include ST_ROOT . '/Views/header.tpl.php';
+        include ST_ROOT . '/Views/statistic.tpl.php';
+        include ST_ROOT . '/Views/footer.tpl.php';
 }

+ 97 - 105
applications/Statistics/Views/main.tpl.php

@@ -9,7 +9,7 @@
 					<a href="/?fn=statistic">监控</a>
 				</li>
 				<li>
-					<a href="/?fn=log">日志</a>
+					<a href="/?fn=logger">日志</a>
 				</li>
 				<li class="disabled">
 					<a href="#">告警</a>
@@ -30,11 +30,11 @@
 	</div>
 	<div class="row clearfix">
 		<div class="col-md-12 column">
-		    <div class="row clearfix">
-		        <div class="col-md-12 column text-center">
-		            <?php echo $date_btn_str;?>
+			<div class="row clearfix">
+				<div class="col-md-12 column text-center">
+					<?php echo $date_btn_str;?>
 				</div>
-		    </div>
+			</div>
 			<div class="row clearfix">
 				<div class="col-md-6 column height-400" id="suc-pie">
 				</div>
@@ -49,107 +49,89 @@
 				<div class="col-md-12 column height-400" id="time-container" >
 				</div>
 			</div>
-			<table class="table table-hover table-condensed table-bordered">
-				<thead>
-					<tr>
-						<th>时间</th><th>调用总数</th><th>平均耗时</th><th>成功调用总数</th><th>成功平均耗时</th><th>失败调用总数</th><th>失败平均耗时</th><th>成功率</th>
-					</tr>
-				</thead>
-				<tbody>
-				<?php echo $table_data;?>
-				</tbody>
-			</table>
-		</div>
-	</div>
-</div>
-<script>
+			<script>
 Highcharts.setOptions({
 	global: {
 		useUTC: false
 	}
 });
-$(function () {
-    $('#suc-pie').highcharts({
-        chart: {
-            plotBackgroundColor: null,
-            plotBorderWidth: null,
-            plotShadow: false
-        },
-        title: {
-            text: '<?php echo $date;?> 可用性'
-        },
-        tooltip: {
-    	    pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
-        },
-        plotOptions: {
-            pie: {
-                allowPointSelect: true,
-                cursor: 'pointer',
-                dataLabels: {
-                    enabled: true,
-                    color: '#000000',
-                    connectorColor: '#000000',
-                    format: '<b>{point.name}</b>: {point.percentage:.1f} %'
-                }
-            }
-        },
-        series: [{
-            type: 'pie',
-            name: '可用性',
-            data: [
-                {
-                    name: '可用',
-                    y: <?php echo $global_rate;?>,
-                    sliced: true,
-                    selected: true,
-                    color: '#2f7ed8'
-                },
-                {
-                    name: '不可用',
-                    y: <?php echo (100-$global_rate);?>,
-                    sliced: true,
-                    selected: true,
-                    color: '#910000'
-                }
-            ]
-        }]
-    });
-});	
-$(function () {
-    $('#code-pie').highcharts({
-        chart: {
-            plotBackgroundColor: null,
-            plotBorderWidth: null,
-            plotShadow: false
-        },
-        title: {
-            text: '<?php echo $date;?> 返回码分布'
-        },
-        tooltip: {
-    	    pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
-        },
-        plotOptions: {
-            pie: {
-                allowPointSelect: true,
-                cursor: 'pointer',
-                dataLabels: {
-                    enabled: true,
-                    color: '#000000',
-                    connectorColor: '#000000',
-                    format: '<b>{point.name}</b>: {point.percentage:.1f} %'
-                }
-            }
-        },
-        series: [{
-            type: 'pie',
-            name: '返回码分布',
-            data: [
-                <?php echo $code_pie_data;?>
-            ]
-        }]
-    });
-});	
-$(function () {
+	$('#suc-pie').highcharts({
+		chart: {
+			plotBackgroundColor: null,
+			plotBorderWidth: null,
+			plotShadow: false
+		},
+		title: {
+			text: '<?php echo $date;?> 可用性'
+		},
+		tooltip: {
+			pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
+		},
+		plotOptions: {
+			pie: {
+				allowPointSelect: true,
+				cursor: 'pointer',
+				dataLabels: {
+					enabled: true,
+					color: '#000000',
+					connectorColor: '#000000',
+					format: '<b>{point.name}</b>: {point.percentage:.1f} %'
+				}
+			}
+		},
+		series: [{
+			type: 'pie',
+			name: '可用性',
+			data: [
+				{
+					name: '可用',
+					y: <?php echo $global_rate;?>,
+					sliced: true,
+					selected: true,
+					color: '#2f7ed8'
+				},
+				{
+					name: '不可用',
+					y: <?php echo (100-$global_rate);?>,
+					sliced: true,
+					selected: true,
+					color: '#910000'
+				}
+			]
+		}]
+	});
+	$('#code-pie').highcharts({
+		chart: {
+			plotBackgroundColor: null,
+			plotBorderWidth: null,
+			plotShadow: false
+		},
+		title: {
+			text: '<?php echo $date;?> 返回码分布'
+		},
+		tooltip: {
+			pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
+		},
+		plotOptions: {
+			pie: {
+				allowPointSelect: true,
+				cursor: 'pointer',
+				dataLabels: {
+					enabled: true,
+					color: '#000000',
+					connectorColor: '#000000',
+					format: '<b>{point.name}</b>: {point.percentage:.1f} %'
+				}
+			}
+		},
+		series: [{
+			type: 'pie',
+			name: '返回码分布',
+			data: [
+				<?php echo $code_pie_data;?>
+			]
+		}]
+	});
 	$('#req-container').highcharts({
 		chart: {
 			type: 'spline'
@@ -208,8 +190,6 @@ $(function () {
 			color : '#9C0D0D'
 		}]
 	});
-});
-$(function () {
 	$('#time-container').highcharts({
 		chart: {
 			type: 'spline'
@@ -269,5 +249,17 @@ $(function () {
 			color : '#9C0D0D'
 		}			]
 	});
-});
-</script>
+</script>
+			<table class="table table-hover table-condensed table-bordered">
+				<thead>
+					<tr>
+						<th>时间</th><th>调用总数</th><th>平均耗时</th><th>成功调用总数</th><th>成功平均耗时</th><th>失败调用总数</th><th>失败平均耗时</th><th>成功率</th>
+					</tr>
+				</thead>
+				<tbody>
+				<?php echo $table_data;?>
+				</tbody>
+			</table>
+		</div>
+	</div>
+</div>

+ 141 - 158
applications/Statistics/Views/statistic.tpl.php

@@ -3,10 +3,13 @@
 		<div class="col-md-12 column">
 			<ul class="nav nav-tabs">
 				<li>
-					<a href="#">概述</a>
+					<a href="/">概述</a>
 				</li>
-				<li class="active">
-					<a href="#">监控</a>
+				<li>
+					<a class="active" href="/?fn=statistic">监控</a>
+				</li>
+				<li>
+					<a href="/?fn=logger">日志</a>
 				</li>
 				<li class="disabled">
 					<a href="#">告警</a>
@@ -27,42 +30,149 @@
 	</div>
 	<div class="row clearfix">
 		<div class="col-md-3 column">
-			<div class="list-group">
-				 <a href="#" class="list-group-item active">HelloWorld</a>
-				 <a href="#" class="list-group-item">sayHello</a>
-				 <a href="#" class="list-group-item">sayHi</a>
-				 <a href="#" class="list-group-item active">User</a>
-				 <a href="#" class="list-group-item active">Blog</a>
-			</div>
+			<ul><?php echo $module_str;?></ul>
 		</div>
 		<div class="col-md-9 column">
-			<div class="alert alert-dismissable alert-success">
-				 <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
-				<h4>
-					Alert!
-				</h4> <strong>Warning!</strong> Best check yo self, you're not looking too good. <a href="#" class="alert-link">alert link</a>
-			</div>
-			<div class="alert alert-dismissable alert-danger">
-				 <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
-				<h4>
-					Alert!
-				</h4> <strong>Warning!</strong> Best check yo self, you're not looking too good. <a href="#" class="alert-link">alert link</a>
-			</div>
-			<h3 class="text-primary text-center">
-				{$module}::{$interface}请求量曲线
-			</h3>
+		<?php if($module && $interface){?>
 			<div class="row clearfix">
-				<div class="col-md-12 column" id="req-container" >
+				<div class="col-md-12 column text-center">
+					<?php echo $date_btn_str;?>
 				</div>
 			</div>
 			<div class="row clearfix">
-				<div class="col-md-12 column" id="time-container" >
+				<div class="col-md-12 column height-400" id="req-container" >
 				</div>
 			</div>
-			<div class="text-center">
-			<button class="btn btn-primary" type="button">分别统计</button>
-			<button class="btn btn-primary" type="button">汇总统计</button>
+			<div class="row clearfix">
+				<div class="col-md-12 column height-400" id="time-container" >
+				</div>
 			</div>
+			<?php if($module && $interface){?>
+			<script>
+			Highcharts.setOptions({
+				global: {
+					useUTC: false
+				}
+			});
+				$('#req-container').highcharts({
+					chart: {
+						type: 'spline'
+					},
+					title: {
+						text: '<?php echo "$date $interface_name";?>  请求量曲线'
+					},
+					subtitle: {
+						text: ''
+					},
+					xAxis: {
+						type: 'datetime',
+						dateTimeLabelFormats: { 
+							hour: '%H:%M'
+						}
+					},
+					yAxis: {
+						title: {
+							text: '请求量(次/5分钟)'
+						},
+						min: 0
+					},
+					tooltip: {
+						formatter: function() {
+							return '<p style="color:'+this.series.color+';font-weight:bold;">'
+							+ this.series.name + 
+							'</p><br /><p style="color:'+this.series.color+';font-weight:bold;">时间:' + Highcharts.dateFormat('%m月%d日 %H:%M', this.x) + 
+							'</p><br /><p style="color:'+this.series.color+';font-weight:bold;">数量:'+ this.y + '</p>';
+						}
+					},
+					credits: {
+						enabled: false,
+					},
+					series: [{
+						name: '成功曲线',
+						data: [
+							<?php echo $success_series_data;?>
+						],
+						lineWidth: 2,
+						marker:{
+							radius: 1
+						},
+						
+						pointInterval: 300*1000
+					},
+					{
+						name: '失败曲线',
+						data: [
+							<?php echo $fail_series_data;?>
+						],
+						lineWidth: 2,
+						marker:{
+							radius: 1
+						},
+						pointInterval: 300*1000,
+						color : '#9C0D0D'
+					}]
+				});
+				$('#time-container').highcharts({
+					chart: {
+						type: 'spline'
+					},
+					title: {
+						text: '<?php echo "$date $interface_name";?>  请求耗时曲线'
+					},
+					subtitle: {
+						text: ''
+					},
+					xAxis: {
+						type: 'datetime',
+						dateTimeLabelFormats: { 
+							hour: '%H:%M'
+						}
+					},
+					yAxis: {
+						title: {
+							text: '平均耗时(单位:秒)'
+						},
+						min: 0
+					},
+					tooltip: {
+						formatter: function() {
+							return '<p style="color:'+this.series.color+';font-weight:bold;">'
+							 + this.series.name + 
+							 '</p><br /><p style="color:'+this.series.color+';font-weight:bold;">时间:' + Highcharts.dateFormat('%m月%d日 %H:%M', this.x) + 
+							 '</p><br /><p style="color:'+this.series.color+';font-weight:bold;">平均耗时:'+ this.y + '</p>';
+						}
+					},
+					credits: {
+						enabled: false,
+						text: "jumei.com",
+						href: "http://www.jumei.com"
+					},
+					series: [{
+						name: '成功曲线',
+						data: [
+							<?php echo $success_time_series_data;?>
+						],
+						lineWidth: 2,
+						marker:{
+							radius: 1
+						},
+						pointInterval: 300*1000
+					},
+					{
+						name: '失败曲线',
+						data: [
+								<?php echo $fail_time_series_data;?>
+						],
+						lineWidth: 2,
+						marker:{
+							radius: 1
+						},
+						pointInterval: 300*1000,
+						color : '#9C0D0D'
+					}]
+				});
+			</script>
+			<?php }?>
 			<table class="table table-hover table-condensed table-bordered">
 				<thead>
 					<tr>
@@ -73,134 +183,7 @@
 				<?php echo $table_data;?>
 				</tbody>
 			</table>
+			<?php }?>
 		</div>
 	</div>
 </div>
-<script>
-Highcharts.setOptions({
-    global: {
-        useUTC: false
-    }
-});
-$(function () {
-    $('#req-container').highcharts({
-        chart: {
-            type: 'spline'
-        },
-        title: {
-            text: '<?php echo "$date $interface_name";?>  请求量曲线'
-        },
-        subtitle: {
-            text: ''
-        },
-        xAxis: {
-            type: 'datetime',
-            dateTimeLabelFormats: { 
-                hour: '%H:%M'
-            }
-        },
-        yAxis: {
-            title: {
-                text: '请求量(次/5分钟)'
-            },
-            min: 0
-        },
-        tooltip: {
-            formatter: function() {
-                return '<p style="color:'+this.series.color+';font-weight:bold;">'
-                 + this.series.name + 
-                 '</p><br /><p style="color:'+this.series.color+';font-weight:bold;">时间:' + Highcharts.dateFormat('%m月%d日 %H:%M', this.x) + 
-                 '</p><br /><p style="color:'+this.series.color+';font-weight:bold;">数量:'+ this.y + '</p>';
-            }
-        },
-        credits: {
-            enabled: false,
-        },
-        series: [        {
-            name: '成功曲线',
-            data: [
-                <?php echo $success_series_data;?>
-            ],
-            lineWidth: 2,
-            marker:{
-                radius: 1
-            },
-            
-            pointInterval: 300*1000
-        },
-        {
-            name: '失败曲线',
-            data: [
-                <?php echo $fail_series_data;?>
-            ],
-            lineWidth: 2,
-            marker:{
-                radius: 1
-            },
-            pointInterval: 300*1000,
-            color : '#9C0D0D'
-        }]
-    });
-});
-$(function () {
-    $('#time-container').highcharts({
-        chart: {
-            type: 'spline'
-        },
-        title: {
-            text: '<?php echo "$date $interface_name";?>  请求耗时曲线'
-        },
-        subtitle: {
-            text: ''
-        },
-        xAxis: {
-            type: 'datetime',
-            dateTimeLabelFormats: { 
-                hour: '%H:%M'
-            }
-        },
-        yAxis: {
-            title: {
-                text: '平均耗时(单位:秒)'
-            },
-            min: 0
-        },
-        tooltip: {
-            formatter: function() {
-                return '<p style="color:'+this.series.color+';font-weight:bold;">'
-                 + this.series.name + 
-                 '</p><br /><p style="color:'+this.series.color+';font-weight:bold;">时间:' + Highcharts.dateFormat('%m月%d日 %H:%M', this.x) + 
-                 '</p><br /><p style="color:'+this.series.color+';font-weight:bold;">平均耗时:'+ this.y + '</p>';
-            }
-        },
-        credits: {
-            enabled: false,
-            text: "jumei.com",
-            href: "http://www.jumei.com"
-        },
-        series: [        {
-            name: '成功曲线',
-            data: [
-                <?php echo $success_time_series_data;?>
-            ],
-            lineWidth: 2,
-            marker:{
-                radius: 1
-            },
-            pointInterval: 300*1000
-        },
-        {
-            name: '失败曲线',
-            data: [
-                   <?php echo $fail_time_series_data;?>
-            ],
-            lineWidth: 2,
-            marker:{
-                radius: 1
-            },
-            pointInterval: 300*1000,
-            color : '#9C0D0D'
-        }            ]
-    });
-});
-</script>

+ 4 - 2
applications/Statistics/Web/index.php

@@ -5,6 +5,7 @@ require_once WORKERMAN_ROOT_DIR .'applications/Statistics/Lib/Cache.php';
 // fn = main/statistic/log/admin
 
 $func = isset($_GET['fn']) ? $_GET['fn'] : 'main';
+$func = "\\Statistics\\Modules\\".$func;
 if(!function_exists($func))
 {
     foreach(glob(ST_ROOT . "/Modules/*") as $php_file)
@@ -15,7 +16,7 @@ if(!function_exists($func))
 
 if(!function_exists($func))
 {
-    $func = 'main';
+    $func = "\\Statistics\\Modules\\main";
 }
 
 $module = isset($_GET['module']) ? $_GET['module'] : '';
@@ -23,4 +24,5 @@ $interface = isset($_GET['interface']) ? $_GET['interface'] : '';
 $date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');
 $start_time = isset($_GET['start_time']) ? $_GET['start_time'] : date('Y-m-d');
 $offset =  isset($_GET['offset']) ? $_GET['offset'] : 0; 
-call_user_func_array($func, array($module, $interface, $date, $start_time, $offset));
+$count =  isset($_GET['count']) ? $_GET['count'] : 10; 
+call_user_func_array($func, array($module, $interface, $date, $start_time, $offset, $count));

+ 1 - 1
conf/workerman.conf

@@ -1,7 +1,7 @@
 ;debug=1则var_dump、echo、php notcie等会在终端上打印出来
 debug=1
 ;保存主进程pid的文件
-pid_file=/var/run/php-server2.pid
+pid_file=/var/run/workerman.pid
 ;日志文件目录
 log_dir=./logs/
 ;共享内存及消息队列用到的key

+ 18 - 13
workers/StatisticProvider.php

@@ -94,7 +94,7 @@ class StatisticProvider extends Man\Core\SocketWorker
                 $this->sendToClient($buffer);
                 break;
             case 'get_log':
-                $buffer = json_encode($this->getStasticLog($module, $interface , $start_time , $end_time, $code = '', $msg = '', $offset='', $count=10))."\n";
+                $buffer = json_encode($this->getStasticLog($module, $interface , $start_time , $end_time, $code, $msg, $offset, $count))."\n";
                 $this->sendToClient($buffer);
                 break;
             default :
@@ -108,7 +108,7 @@ class StatisticProvider extends Man\Core\SocketWorker
      */
     public function getModules($current_module = '')
     {
-        $st_dir = WORKERMAN_ROOT_DIR . $this->statisticDir;
+        $st_dir = WORKERMAN_LOG_DIR . $this->statisticDir;
         $modules_name_array = array();
         foreach(glob($st_dir."/*", GLOB_ONLYDIR) as $module_file)
         {
@@ -160,23 +160,23 @@ class StatisticProvider extends Man\Core\SocketWorker
     protected function getStasticLog($module, $interface , $start_time = '', $end_time = '', $code = '', $msg = '', $offset='', $count=100)
     {
         // log文件
-        $log_file = WORKERMAN_ROOT_DIR . $this->logDir. (empty($start_time) ? date('Y-m-d') : date('Y-m-d', $start_time));
+        $log_file = WORKERMAN_LOG_DIR . $this->logDir. (empty($start_time) ? date('Y-m-d') : date('Y-m-d', $start_time));
         if(!is_readable($log_file))
         {
-            return array('offset'=>0, 'data'=>$log_file . 'not exists or not readable');
+            return array('offset'=>0, 'data'=>'');
         }
         // 读文件
         $h = fopen($log_file, 'r');
     
         // 如果有时间,则进行二分查找,加速查询
-        if($start_time && $offset === '' && ($file_size = filesize($log_file) > 50000))
+        if($start_time && $offset == 0 && ($file_size = filesize($log_file)) > 1024000)
         {
             $offset = $this->binarySearch(0, $file_size, $start_time-1, $h);
-            $offset = $offset < 1000 ? 0 : $offset - 1000;
+            $offset = $offset < 100000 ? 0 : $offset - 100000;
         }
     
         // 正则表达式
-        $pattern = "/^([\d: \-]+)\t";
+        $pattern = "/^([\d: \-]+)\t\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\t";
     
         if($module && $module != 'WorkerMan')
         {
@@ -213,9 +213,9 @@ class StatisticProvider extends Man\Core\SocketWorker
         $pattern .= '/';
     
         // 指定偏移位置
-        if($offset >= 0)
+        if($offset > 0)
         {
-            fseek($h, (int)$offset);
+            fseek($h, (int)$offset-1);
         }
     
         // 查找符合条件的数据
@@ -270,31 +270,36 @@ class StatisticProvider extends Man\Core\SocketWorker
      */
     protected function binarySearch($start_point, $end_point, $time, $fd)
     {
+        if($end_point - $start_point < 65535)
+        {
+            return $start_point;
+        }
+        
         // 计算中点
         $mid_point = (int)(($end_point+$start_point)/2);
     
         // 定位文件指针在中点
-        fseek($fd, $mid_point);
+        fseek($fd, $mid_point - 1);
     
         // 读第一行
         $line = fgets($fd);
         if(feof($fd) || false === $line)
         {
-            return ftell($fd);
+            return $start_point;
         }
     
         // 第一行可能数据不全,再读一行
         $line = fgets($fd);
         if(feof($fd) || false === $line || trim($line) == '')
         {
-            return ftell($fd);
+            return $start_point;
         }
     
         // 判断是否越界
         $current_point = ftell($fd);
         if($current_point>=$end_point)
         {
-            return $end_point;
+            return $start_point;
         }
     
         // 获得时间