Przeglądaj źródła

auto update script executed

Toby Chui 1 rok temu
rodzic
commit
c383e064a4
5 zmienionych plików z 70 dodań i 52 usunięć
  1. 2 1
      api.go
  2. 3 0
      main.go
  3. 33 5
      mod/netstat/netstat.go
  4. 8 0
      start.go
  5. 24 46
      web/components/status.html

+ 2 - 1
api.go

@@ -75,6 +75,7 @@ func initAPIs() {
 	authRouter.HandleFunc("/api/stats/summary", statisticCollector.HandleTodayStatLoad)
 	authRouter.HandleFunc("/api/stats/countries", HandleCountryDistrSummary)
 	authRouter.HandleFunc("/api/stats/netstat", netstat.HandleGetNetworkInterfaceStats)
+	authRouter.HandleFunc("/api/stats/netstatgraph", netstatBuffers.HandleGetBufferedNetworkInterfaceStats)
 	authRouter.HandleFunc("/api/stats/listnic", netstat.HandleListNetworkInterfaces)
 	authRouter.HandleFunc("/api/utm/list", HandleUptimeMonitorListing)
 
@@ -113,7 +114,7 @@ func initAPIs() {
 	//If you got APIs to add, append them here
 }
 
-//Function to renders Auth related APIs
+// Function to renders Auth related APIs
 func registerAuthAPIs(requireAuth bool) {
 	//Auth APIs
 	http.HandleFunc("/api/auth/login", authAgent.HandleLogin)

+ 3 - 0
main.go

@@ -20,6 +20,7 @@ import (
 	"imuslab.com/zoraxy/mod/ganserv"
 	"imuslab.com/zoraxy/mod/geodb"
 	"imuslab.com/zoraxy/mod/mdns"
+	"imuslab.com/zoraxy/mod/netstat"
 	"imuslab.com/zoraxy/mod/sshprox"
 	"imuslab.com/zoraxy/mod/statistic"
 	"imuslab.com/zoraxy/mod/tlscert"
@@ -54,6 +55,7 @@ var (
 	tlsCertManager     *tlscert.Manager        //TLS / SSL management
 	redirectTable      *redirection.RuleTable  //Handle special redirection rule sets
 	geodbStore         *geodb.Store            //GeoIP database
+	netstatBuffers     *netstat.NetStatBuffers //Realtime graph buffers
 	statisticCollector *statistic.Collector    //Collecting statistic from visitors
 	uptimeMonitor      *uptime.Monitor         //Uptime monitor service worker
 	mdnsScanner        *mdns.MDNSHost          //mDNS discovery services
@@ -70,6 +72,7 @@ func SetupCloseHandler() {
 		<-c
 		log.Println("\r- Shutting down " + name)
 		geodbStore.Close()
+		netstatBuffers.Close()
 		statisticCollector.Close()
 		//Stop the mdns service
 		mdnsTickerStop <- true

+ 33 - 5
mod/netstat/netstat.go

@@ -33,6 +33,7 @@ type NetStatBuffers struct {
 	PreviousStat    *RawFlowStat //The value of the last instance of netstats
 	Stats           []*FlowStat  //Statistic of the flow
 	StopChan        chan bool    //Channel to stop the ticker
+	EventTicker     *time.Ticker //Ticker for event logging
 }
 
 // Get a new network statistic buffers
@@ -58,7 +59,6 @@ func NewNetStatBuffer(recordCount int) (*NetStatBuffers, error) {
 
 	//Setup a timer to get the value from NIC accumulation stats
 	ticker := time.NewTicker(time.Second)
-	defer ticker.Stop()
 
 	//Setup a stop channel
 	stopCh := make(chan bool)
@@ -68,6 +68,7 @@ func NewNetStatBuffer(recordCount int) (*NetStatBuffers, error) {
 		PreviousStat:    &currnetNetSpec,
 		Stats:           initialStats,
 		StopChan:        stopCh,
+		EventTicker:     ticker,
 	}
 
 	// Update the buffer every second
@@ -102,8 +103,10 @@ func NewNetStatBuffer(recordCount int) (*NetStatBuffers, error) {
 					TX: tx,
 				}
 
-				copy(initialStats, initialStats[1:])
-				initialStats = append(initialStats, newStat)
+				newStats := n.Stats[1:]
+				newStats = append(newStats, newStat)
+
+				n.Stats = newStats
 			}
 		}
 	}(&thisNetBuffer)
@@ -112,12 +115,37 @@ func NewNetStatBuffer(recordCount int) (*NetStatBuffers, error) {
 }
 
 func (n *NetStatBuffers) HandleGetBufferedNetworkInterfaceStats(w http.ResponseWriter, r *http.Request) {
-	js, _ := json.Marshal(n.Stats)
-	utils.SendJSONResponse(w, string(js))
+	arr, _ := utils.GetPara(r, "array")
+	if arr == "true" {
+		//Restructure it into array
+		rx := []int{}
+		tx := []int{}
+
+		for _, state := range n.Stats {
+			rx = append(rx, int(state.RX))
+			tx = append(tx, int(state.TX))
+		}
+
+		type info struct {
+			Rx []int
+			Tx []int
+		}
+
+		js, _ := json.Marshal(info{
+			Rx: rx,
+			Tx: tx,
+		})
+		utils.SendJSONResponse(w, string(js))
+	} else {
+		js, _ := json.Marshal(n.Stats)
+		utils.SendJSONResponse(w, string(js))
+	}
+
 }
 
 func (n *NetStatBuffers) Close() {
 	n.StopChan <- true
+	n.EventTicker.Stop()
 }
 
 func HandleGetNetworkInterfaceStats(w http.ResponseWriter, r *http.Request) {

+ 8 - 0
start.go

@@ -14,6 +14,7 @@ import (
 	"imuslab.com/zoraxy/mod/ganserv"
 	"imuslab.com/zoraxy/mod/geodb"
 	"imuslab.com/zoraxy/mod/mdns"
+	"imuslab.com/zoraxy/mod/netstat"
 	"imuslab.com/zoraxy/mod/sshprox"
 	"imuslab.com/zoraxy/mod/statistic"
 	"imuslab.com/zoraxy/mod/tlscert"
@@ -87,6 +88,13 @@ func startupSequence() {
 		panic(err)
 	}
 
+	//Create a netstat buffer
+	netstatBuffers, err = netstat.NewNetStatBuffer(300)
+	if err != nil {
+		log.Println("Failed to load network statistic info")
+		panic(err)
+	}
+
 	/*
 		MDNS Discovery Service
 

+ 24 - 46
web/components/status.html

@@ -395,58 +395,38 @@
 
     let rxValues = [];
     let txValues = [];
-    let lastRx = 0;
-    let lastTx = 0;
+    let dataCount = 300;
     let timestamps = [];
-    let netstatRecordTokeep = 60;
 
-    function fetchData() {
-        fetch('/api/stats/netstat')
-        .then(response => response.json())
-        .then(data => {
-            let rx = data.RX;
-            let tx = data.TX;
-
-            // Calculate change from previous values
-            if (lastRx == 0 && lastTx == 0){
-                //inital value
-                lastRx = rx;
-                lastTx = tx;
-                return;
-            }
-
-            let deltaRx = rx - lastRx;
-            let deltaTx = tx - lastTx;
+    for(var i = 0; i < dataCount; i++){
+        timestamps.push(parseInt(Date.now() / 1000) + i);
+    }
 
-            if (rxValues.length < netstatRecordTokeep){
-                //pad init into the array
-                for(var i = 0;i<netstatRecordTokeep;i++){
-                    rxValues.push(deltaRx);
-                    txValues.push(deltaTx);
-                    timestamps.push(Date.now() - 1000 * (netstatRecordTokeep - i))
+    function fetchData() {
+        $.ajax({
+            url: '/api/stats/netstatgraph?array=true',
+            success: function(data){
+                if (rxValues.length == 0){
+                    rxValues = JSON.parse(JSON.stringify(data.Rx));
+                }else{
+                    rxValues.push(data.Rx[dataCount-1]);
+                    rxValues.shift();
                 }
-            }
-
-            // Add change to accumulated values
-            rxValues.push(deltaRx);
-            txValues.push(deltaTx);
-            timestamps.push(Date.now());
 
-            // Only keep last netstatRecordTokeep data points
-            if (rxValues.length > netstatRecordTokeep) {
-                rxValues.shift();
-                txValues.shift();
+                if (txValues.length == 0){
+                    txValues = JSON.parse(JSON.stringify(data.Tx));
+                }else{
+                    txValues.push(data.Tx[dataCount-1]);
+                    txValues.shift();
+                }
+                
+               
+                timestamps.push(parseInt(Date.now() / 1000));
                 timestamps.shift();
-            }
-
-            lastRx = rx;
-            lastTx = tx;
 
-            updateChart();
+                updateChart();
+            }
         })
-        .catch(error => {
-            //console.error('Failed to fetch data', error);
-        });
     }
 
     function formatBandwidth(bps) {
@@ -546,7 +526,6 @@
         if (networkStatisticChart != undefined){
             networkStatisticChart.update();
         }
-        
     }
 
     function updateChartSize(){
@@ -600,7 +579,6 @@
     });
 
 
-
     //Initialize chart data
     initChart();
     fetchData();