优化稳定性
This commit is contained in:
@@ -31,6 +31,22 @@
|
||||
|
||||
|
||||
# 更新日志
|
||||
- 2026-06-04 v0.26.34
|
||||
- 修复:
|
||||
- Dashboard IO 速率采集阻塞请求 500ms,改为后台采集缓存,消除 Sleep 等待
|
||||
- ServerStatus 切片并发读写不安全,添加 RWMutex 保护
|
||||
- flowSession goroutine 泄漏,改为仅在 StartNewServer 启动一次
|
||||
- GetTunnel 双重遍历 sync.Map 性能问题,合并为单次 Range
|
||||
- Bridge Client 字段并发读写不安全,添加 Mutex 保护
|
||||
- TLS ClientHello recordLen 无上限,添加 16KB 限制防止内存耗尽
|
||||
- SOCKS5 地址解析未检查 Read 返回值,改用 io.ReadFull
|
||||
- 文件存储 panic 改为错误日志,defer 清理临时文件防止泄漏
|
||||
- GenerateServerPort 可能无限循环,限制 1000 次重试
|
||||
- P2P UDP 无超时永久阻塞,添加 30s ReadDeadline
|
||||
- P2P goroutine 退出控制改用 context,修复潜在泄漏
|
||||
- 客户端 UDP ReadFrom 错误后未退出,修复无效数据继续处理
|
||||
- 优化:ioutil.WriteFile → os.WriteFile、rand.Seed → rand.New 本地随机源
|
||||
|
||||
- 2026-05-23 v0.26.33
|
||||
- 新增:
|
||||
- 配置文件自动生成:启动时若 conf 目录或 nps.conf 不存在,自动创建并写入默认配置,方便 Docker 部署
|
||||
|
||||
+51
-18
@@ -12,6 +12,7 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"ehang.io/nps/lib/common"
|
||||
@@ -28,11 +29,12 @@ import (
|
||||
var ServerTlsEnable bool = false
|
||||
|
||||
type Client struct {
|
||||
mu sync.Mutex // 保护 signal/tunnel/Version 等字段的并发读写
|
||||
tunnel *nps_mux.Mux
|
||||
signal *conn.Conn
|
||||
file *nps_mux.Mux
|
||||
Version string
|
||||
retryTime int // it will be add 1 when ping not ok until to 3 will close the client
|
||||
retryTime atomic.Int32 // it will be add 1 when ping not ok until to 3 will close the client
|
||||
}
|
||||
|
||||
func NewClient(t, f *nps_mux.Mux, s *conn.Conn, vs string) *Client {
|
||||
@@ -237,8 +239,13 @@ func (s *Bridge) cliProcess(c *conn.Conn) {
|
||||
|
||||
func (s *Bridge) DelClient(id int) {
|
||||
if v, ok := s.Client.Load(id); ok {
|
||||
if v.(*Client).signal != nil {
|
||||
v.(*Client).signal.Close()
|
||||
cl := v.(*Client)
|
||||
cl.mu.Lock()
|
||||
signalToClose := cl.signal
|
||||
cl.signal = nil
|
||||
cl.mu.Unlock()
|
||||
if signalToClose != nil {
|
||||
signalToClose.Close()
|
||||
}
|
||||
s.Client.Delete(id)
|
||||
if file.GetDb().IsPubClient(id) {
|
||||
@@ -267,18 +274,26 @@ func (s *Bridge) typeDeal(typeVal string, c *conn.Conn, id int, vs string) {
|
||||
}
|
||||
//the vKey connect by another ,close the client of before
|
||||
if v, ok := s.Client.LoadOrStore(id, NewClient(nil, nil, c, vs)); ok {
|
||||
if v.(*Client).signal != nil {
|
||||
v.(*Client).signal.WriteClose()
|
||||
cl := v.(*Client)
|
||||
cl.mu.Lock()
|
||||
oldSignal := cl.signal
|
||||
cl.signal = c
|
||||
cl.Version = vs
|
||||
cl.mu.Unlock()
|
||||
cl.retryTime.Store(0)
|
||||
if oldSignal != nil {
|
||||
oldSignal.WriteClose()
|
||||
}
|
||||
v.(*Client).signal = c
|
||||
v.(*Client).Version = vs
|
||||
}
|
||||
go s.GetHealthFromClient(id, c)
|
||||
logs.Info("clientId %d connection succeeded, address:%s ", id, c.Conn.RemoteAddr())
|
||||
case common.WORK_CHAN:
|
||||
muxConn := nps_mux.NewMux(c.Conn, s.tunnelType, s.disconnectTime)
|
||||
if v, ok := s.Client.LoadOrStore(id, NewClient(muxConn, nil, nil, vs)); ok {
|
||||
v.(*Client).tunnel = muxConn
|
||||
cl := v.(*Client)
|
||||
cl.mu.Lock()
|
||||
cl.tunnel = muxConn
|
||||
cl.mu.Unlock()
|
||||
}
|
||||
case common.WORK_CONFIG:
|
||||
client, err := file.GetDb().GetClient(id)
|
||||
@@ -299,7 +314,10 @@ func (s *Bridge) typeDeal(typeVal string, c *conn.Conn, id int, vs string) {
|
||||
case common.WORK_FILE:
|
||||
muxConn := nps_mux.NewMux(c.Conn, s.tunnelType, s.disconnectTime)
|
||||
if v, ok := s.Client.LoadOrStore(id, NewClient(nil, muxConn, nil, vs)); ok {
|
||||
v.(*Client).file = muxConn
|
||||
cl := v.(*Client)
|
||||
cl.mu.Lock()
|
||||
cl.file = muxConn
|
||||
cl.mu.Unlock()
|
||||
}
|
||||
case common.WORK_P2P:
|
||||
//read md5 secret
|
||||
@@ -311,15 +329,22 @@ func (s *Bridge) typeDeal(typeVal string, c *conn.Conn, id int, vs string) {
|
||||
if v, ok := s.Client.Load(t.Client.Id); !ok {
|
||||
return
|
||||
} else {
|
||||
cl := v.(*Client)
|
||||
cl.mu.Lock()
|
||||
sig := cl.signal
|
||||
cl.mu.Unlock()
|
||||
if sig == nil {
|
||||
return
|
||||
}
|
||||
//向密钥对应的客户端发送与服务端udp建立连接信息,地址,密钥
|
||||
v.(*Client).signal.Write([]byte(common.NEW_UDP_CONN))
|
||||
sig.Write([]byte(common.NEW_UDP_CONN))
|
||||
svrAddr := beego.AppConfig.String("p2p_ip") + ":" + beego.AppConfig.String("p2p_port")
|
||||
if err != nil {
|
||||
logs.Warn("get local udp addr error")
|
||||
return
|
||||
}
|
||||
v.(*Client).signal.WriteLenContent([]byte(svrAddr))
|
||||
v.(*Client).signal.WriteLenContent(b)
|
||||
sig.WriteLenContent([]byte(svrAddr))
|
||||
sig.WriteLenContent(b)
|
||||
//向该请求者发送建立连接请求,服务器地址
|
||||
c.WriteLenContent([]byte(svrAddr))
|
||||
}
|
||||
@@ -356,11 +381,14 @@ func (s *Bridge) SendLinkInfo(clientId int, link *conn.Link, t *file.Tunnel) (ta
|
||||
}
|
||||
}
|
||||
var tunnel *nps_mux.Mux
|
||||
cl := v.(*Client)
|
||||
cl.mu.Lock()
|
||||
if t != nil && t.Mode == "file" {
|
||||
tunnel = v.(*Client).file
|
||||
tunnel = cl.file
|
||||
} else {
|
||||
tunnel = v.(*Client).tunnel
|
||||
tunnel = cl.tunnel
|
||||
}
|
||||
cl.mu.Unlock()
|
||||
if tunnel == nil {
|
||||
err = errors.New("the client connect error")
|
||||
return
|
||||
@@ -393,14 +421,19 @@ func (s *Bridge) ping() {
|
||||
arr := make([]int, 0)
|
||||
s.Client.Range(func(key, value interface{}) bool {
|
||||
v := value.(*Client)
|
||||
if v.tunnel == nil || v.signal == nil {
|
||||
v.retryTime += 1
|
||||
if v.retryTime >= 3 {
|
||||
v.mu.Lock()
|
||||
tunnel := v.tunnel
|
||||
signal := v.signal
|
||||
if tunnel == nil || signal == nil {
|
||||
v.mu.Unlock()
|
||||
if v.retryTime.Add(1) >= 3 {
|
||||
arr = append(arr, key.(int))
|
||||
}
|
||||
return true
|
||||
}
|
||||
if v.tunnel.IsClose {
|
||||
isClose := tunnel.IsClose()
|
||||
v.mu.Unlock()
|
||||
if isClose {
|
||||
arr = append(arr, key.(int))
|
||||
}
|
||||
return true
|
||||
|
||||
+6
-4
@@ -324,20 +324,22 @@ func (s *TRPClient) handleUdp(serverConn net.Conn) {
|
||||
defer serverConn.Close()
|
||||
b := common.BufPoolUdp.Get().([]byte)
|
||||
defer common.BufPoolUdp.Put(b)
|
||||
var buf bytes.Buffer
|
||||
for {
|
||||
n, raddr, err := local.ReadFrom(b)
|
||||
if err != nil {
|
||||
s.logError("read data from remote server error %s", err.Error())
|
||||
return
|
||||
}
|
||||
buf := bytes.Buffer{}
|
||||
buf.Reset()
|
||||
dgram := common.NewUDPDatagram(common.NewUDPHeader(0, 0, common.ToSocksAddr(raddr)), b[:n])
|
||||
dgram.Write(&buf)
|
||||
b, err := conn.GetLenBytes(buf.Bytes())
|
||||
data, err := conn.GetLenBytes(buf.Bytes())
|
||||
if err != nil {
|
||||
s.logWarn("get len bytes error %s", err.Error())
|
||||
continue
|
||||
}
|
||||
if _, err := serverConn.Write(b); err != nil {
|
||||
if _, err := serverConn.Write(data); err != nil {
|
||||
s.logError("write data to remote error %s", err.Error())
|
||||
return
|
||||
}
|
||||
@@ -377,7 +379,7 @@ loop:
|
||||
for {
|
||||
select {
|
||||
case <-s.ticker.C:
|
||||
if s.tunnel != nil && s.tunnel.IsClose {
|
||||
if s.tunnel != nil && s.tunnel.IsClose() {
|
||||
s.Close()
|
||||
break loop
|
||||
}
|
||||
|
||||
+33
-30
@@ -2,12 +2,12 @@ package client
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"math"
|
||||
"math/rand"
|
||||
@@ -147,7 +147,7 @@ re:
|
||||
}
|
||||
vkey = string(b)
|
||||
}
|
||||
ioutil.WriteFile(filepath.Join(common.GetTmpPath(), "npc_vkey.txt"), []byte(vkey), 0600)
|
||||
os.WriteFile(filepath.Join(common.GetTmpPath(), "npc_vkey.txt"), []byte(vkey), 0600)
|
||||
|
||||
//send hosts to server
|
||||
for _, v := range cnf.Hosts {
|
||||
@@ -343,6 +343,7 @@ func handleP2PUdp(localAddr, rAddr, md5Password, role string) (remoteAddress str
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer localConn.Close()
|
||||
err = getRemoteAddressFromServer(rAddr, localConn, md5Password, role, 0)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
@@ -359,27 +360,32 @@ func handleP2PUdp(localAddr, rAddr, md5Password, role string) (remoteAddress str
|
||||
return
|
||||
}
|
||||
var remoteAddr1, remoteAddr2, remoteAddr3 string
|
||||
// 修复:添加超时,避免无限等待远端响应
|
||||
localConn.SetReadDeadline(time.Now().Add(30 * time.Second))
|
||||
buf := make([]byte, 1024)
|
||||
for {
|
||||
buf := make([]byte, 1024)
|
||||
if n, addr, er := localConn.ReadFromUDP(buf); er != nil {
|
||||
err = er
|
||||
var n int
|
||||
var addr *net.UDPAddr
|
||||
n, addr, err = localConn.ReadFromUDP(buf)
|
||||
if err != nil {
|
||||
localConn.SetReadDeadline(time.Time{})
|
||||
return
|
||||
} else {
|
||||
rAddr2, _ := getNextAddr(rAddr, 1)
|
||||
rAddr3, _ := getNextAddr(rAddr, 2)
|
||||
switch addr.String() {
|
||||
case rAddr:
|
||||
remoteAddr1 = string(buf[:n])
|
||||
case rAddr2:
|
||||
remoteAddr2 = string(buf[:n])
|
||||
case rAddr3:
|
||||
remoteAddr3 = string(buf[:n])
|
||||
}
|
||||
}
|
||||
rAddr2, _ := getNextAddr(rAddr, 1)
|
||||
rAddr3, _ := getNextAddr(rAddr, 2)
|
||||
switch addr.String() {
|
||||
case rAddr:
|
||||
remoteAddr1 = string(buf[:n])
|
||||
case rAddr2:
|
||||
remoteAddr2 = string(buf[:n])
|
||||
case rAddr3:
|
||||
remoteAddr3 = string(buf[:n])
|
||||
}
|
||||
if remoteAddr1 != "" && remoteAddr2 != "" && remoteAddr3 != "" {
|
||||
break
|
||||
}
|
||||
}
|
||||
localConn.SetReadDeadline(time.Time{})
|
||||
if remoteAddress, err = sendP2PTestMsg(localConn, remoteAddr1, remoteAddr2, remoteAddr3); err != nil {
|
||||
return
|
||||
}
|
||||
@@ -389,9 +395,8 @@ func handleP2PUdp(localAddr, rAddr, md5Password, role string) (remoteAddress str
|
||||
|
||||
func sendP2PTestMsg(localConn *net.UDPConn, remoteAddr1, remoteAddr2, remoteAddr3 string) (string, error) {
|
||||
logs.Trace(remoteAddr3, remoteAddr2, remoteAddr1)
|
||||
defer localConn.Close()
|
||||
isClose := false
|
||||
defer func() { isClose = true }()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
interval, err := getAddrInterval(remoteAddr1, remoteAddr2, remoteAddr3)
|
||||
if err != nil {
|
||||
return "", err
|
||||
@@ -410,10 +415,9 @@ func sendP2PTestMsg(localConn *net.UDPConn, remoteAddr1, remoteAddr2, remoteAddr
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
if isClose {
|
||||
return
|
||||
}
|
||||
if _, err := localConn.WriteTo([]byte(common.WORK_P2P_CONNECT), remoteUdpAddr); err != nil {
|
||||
return
|
||||
}
|
||||
@@ -436,10 +440,9 @@ func sendP2PTestMsg(localConn *net.UDPConn, remoteAddr1, remoteAddr2, remoteAddr
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
if isClose {
|
||||
return
|
||||
}
|
||||
if _, err := localConn.WriteTo([]byte(common.WORK_P2P_CONNECT), remoteUdpAddr); err != nil {
|
||||
return
|
||||
}
|
||||
@@ -552,13 +555,13 @@ func getRandomPortArr(min, max int) []int {
|
||||
for i := min; i <= max; i++ {
|
||||
addrAddr[max-i] = i
|
||||
}
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
var r, temp int
|
||||
r := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
var ri, temp int
|
||||
for i := max - min; i > 0; i-- {
|
||||
r = rand.Int() % i
|
||||
ri = r.Int() % i
|
||||
temp = addrAddr[i]
|
||||
addrAddr[i] = addrAddr[r]
|
||||
addrAddr[r] = temp
|
||||
addrAddr[i] = addrAddr[ri]
|
||||
addrAddr[ri] = temp
|
||||
}
|
||||
return addrAddr
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,2 +1,2 @@
|
||||
{"Cnf":{"U":"","P":"","Compress":false,"Crypt":false},"Id":2,"VerifyKey":"aceecc399e","Addr":"127.0.0.1","Remark":"","Status":true,"IsConnect":true,"RateLimit":0,"Flow":{"ExportFlow":7888065,"InletFlow":7888065,"FlowLimit":0},"Rate":{"NowRate":17179869184},"NoStore":false,"NoDisplay":false,"MaxConn":0,"NowConn":0,"WebUserName":"","WebPassword":"","ConfigConnAllow":true,"MaxTunnelNum":0,"Version":"0.26.19","BlackIpList":[],"CreateTime":"2026-05-14 16:37:55","LastOnlineTime":"2026-05-14 17:30:13","IpWhite":false,"IpWhitePass":"","IpWhiteList":[]}
|
||||
{"Cnf":{"U":"","P":"","Compress":false,"Crypt":false},"Id":4,"VerifyKey":"02cea9bedf","Addr":"127.0.0.1","Remark":"","Status":true,"IsConnect":true,"RateLimit":0,"Flow":{"ExportFlow":1405996,"InletFlow":1405996,"FlowLimit":0},"Rate":{"NowRate":0},"NoStore":false,"NoDisplay":false,"MaxConn":0,"NowConn":6,"WebUserName":"","WebPassword":"","ConfigConnAllow":true,"MaxTunnelNum":0,"Version":"0.26.34","BlackIpList":[],"CreateTime":"2026-06-05 15:54:21","LastOnlineTime":"2026-06-05 15:55:40","IpWhite":false,"IpWhitePass":"","IpWhiteList":[]}
|
||||
*#*
|
||||
+1
-1
@@ -1,2 +1,2 @@
|
||||
{"Id":1,"Port":33833,"ServerIp":"0.0.0.0","Mode":"tcp","Status":true,"RunStatus":true,"Client":{"Cnf":{"U":"","P":"","Compress":false,"Crypt":false},"Id":2,"VerifyKey":"aceecc399e","Addr":"127.0.0.1","Remark":"","Status":true,"IsConnect":true,"RateLimit":0,"Flow":{"ExportFlow":7888065,"InletFlow":7888065,"FlowLimit":0},"Rate":{"NowRate":0},"NoStore":false,"NoDisplay":false,"MaxConn":0,"NowConn":0,"WebUserName":"","WebPassword":"","ConfigConnAllow":true,"MaxTunnelNum":0,"Version":"0.26.19","BlackIpList":[],"CreateTime":"2026-05-14 16:37:55","LastOnlineTime":"2026-05-14 17:30:13","IpWhite":false,"IpWhitePass":"","IpWhiteList":[]},"Ports":"","Flow":{"ExportFlow":0,"InletFlow":0,"FlowLimit":0},"Password":"","Remark":"","TargetAddr":"","NoStore":false,"LocalPath":"","StripPre":"","ProtoVersion":"","Target":{"TargetStr":"192.168.225.103:8081","TargetArr":["192.168.225.103:8081"],"LocalProxy":false},"MultiAccount":null,"HealthCheckTimeout":0,"HealthMaxFail":0,"HealthCheckInterval":0,"HealthNextTime":"0001-01-01T00:00:00Z","HealthMap":null,"HttpHealthUrl":"","HealthRemoveArr":null,"HealthCheckType":"","HealthCheckTarget":""}
|
||||
{"Id":2,"Port":44263,"ServerIp":"0.0.0.0","Mode":"tcp","Status":true,"RunStatus":true,"Client":{"Cnf":{"U":"","P":"","Compress":false,"Crypt":false},"Id":4,"VerifyKey":"02cea9bedf","Addr":"127.0.0.1","Remark":"","Status":true,"IsConnect":true,"RateLimit":0,"Flow":{"ExportFlow":1405996,"InletFlow":1405996,"FlowLimit":0},"Rate":{"NowRate":0},"NoStore":false,"NoDisplay":false,"MaxConn":0,"NowConn":6,"WebUserName":"","WebPassword":"","ConfigConnAllow":true,"MaxTunnelNum":0,"Version":"0.26.34","BlackIpList":[],"CreateTime":"2026-06-05 15:54:21","LastOnlineTime":"2026-06-05 15:55:40","IpWhite":false,"IpWhitePass":"","IpWhiteList":[]},"Ports":"","Flow":{"ExportFlow":0,"InletFlow":0,"FlowLimit":0},"Password":"","Remark":"","TargetAddr":"","NoStore":false,"LocalPath":"","StripPre":"","ProtoVersion":"","Target":{"TargetStr":"127.0.0.1:8081","TargetArr":["127.0.0.1:8081"],"LocalProxy":false},"MultiAccount":null,"HealthCheckTimeout":0,"HealthMaxFail":0,"HealthCheckInterval":0,"HealthNextTime":"0001-01-01T00:00:00Z","HealthMap":null,"HttpHealthUrl":"","HealthRemoveArr":null,"HealthCheckType":"","HealthCheckTarget":""}
|
||||
*#*
|
||||
+28
-11
@@ -187,8 +187,14 @@ func storeSyncMapToFile(m sync.Map, filePath string) {
|
||||
file, err := os.Create(filePath + ".tmp")
|
||||
// first create a temporary file to store
|
||||
if err != nil {
|
||||
panic(err)
|
||||
logs.Error("store to file: create tmp file error: %v", err)
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
file.Close()
|
||||
os.Remove(filePath + ".tmp")
|
||||
}()
|
||||
var writeErr bool
|
||||
m.Range(func(key, value interface{}) bool {
|
||||
var b []byte
|
||||
var err error
|
||||
@@ -211,9 +217,6 @@ func storeSyncMapToFile(m sync.Map, filePath string) {
|
||||
return true
|
||||
}
|
||||
b, err = json.Marshal(obj)
|
||||
//case *Glob:
|
||||
// obj := value.(*Glob)
|
||||
// b, err = json.Marshal(obj)
|
||||
default:
|
||||
return true
|
||||
}
|
||||
@@ -222,40 +225,54 @@ func storeSyncMapToFile(m sync.Map, filePath string) {
|
||||
}
|
||||
_, err = file.Write(b)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
logs.Error("store to file: write error: %v", err)
|
||||
writeErr = true
|
||||
return false
|
||||
}
|
||||
_, err = file.Write([]byte("\n" + common.CONN_DATA_SEQ))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
logs.Error("store to file: write separator error: %v", err)
|
||||
writeErr = true
|
||||
return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
if writeErr {
|
||||
return
|
||||
}
|
||||
_ = file.Sync()
|
||||
_ = file.Close()
|
||||
// must close file first, then rename it
|
||||
err = os.Rename(filePath+".tmp", filePath)
|
||||
if err != nil {
|
||||
logs.Error(err, "store to file err, data will lost")
|
||||
}
|
||||
// replace the file, maybe provides atomic operation
|
||||
}
|
||||
|
||||
func storeGlobalToFile(m *Glob, filePath string) {
|
||||
file, err := os.Create(filePath + ".tmp")
|
||||
// first create a temporary file to store
|
||||
if err != nil {
|
||||
panic(err)
|
||||
logs.Error("store global to file: create tmp file error: %v", err)
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
file.Close()
|
||||
os.Remove(filePath + ".tmp")
|
||||
}()
|
||||
|
||||
var b []byte
|
||||
b, err = json.Marshal(m)
|
||||
if err != nil {
|
||||
logs.Error("store global to file: marshal error: %v", err)
|
||||
return
|
||||
}
|
||||
_, err = file.Write(b)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
logs.Error("store global to file: write error: %v", err)
|
||||
return
|
||||
}
|
||||
_ = file.Sync()
|
||||
_ = file.Close()
|
||||
// must close file first, then rename it
|
||||
err = os.Rename(filePath+".tmp", filePath)
|
||||
if err != nil {
|
||||
logs.Error(err, "store to file err, data will lost")
|
||||
|
||||
+1
-1
@@ -72,7 +72,7 @@ func (s *conn) Close() (err error) {
|
||||
func (s *conn) closeProcess() {
|
||||
s.isClose = true
|
||||
s.receiveWindow.mux.connMap.Delete(s.connId)
|
||||
if !s.receiveWindow.mux.IsClose {
|
||||
if !s.receiveWindow.mux.IsClose() {
|
||||
// if server or user close the conn while reading, will Get a io.EOF
|
||||
// and this Close method will be invoke, send this signal to close other side
|
||||
s.receiveWindow.mux.sendInfo(muxConnClose, s.connId, nil)
|
||||
|
||||
+18
-16
@@ -35,7 +35,7 @@ type Mux struct {
|
||||
newConnCh chan *conn
|
||||
id int32
|
||||
closeChan chan struct{}
|
||||
IsClose bool
|
||||
isClose atomic.Bool
|
||||
counter *latencyCounter
|
||||
bw *bandwidth
|
||||
pingCh chan []byte
|
||||
@@ -70,7 +70,6 @@ func NewMux(c net.Conn, connType string, pingCheckThreshold int) *Mux {
|
||||
closeChan: make(chan struct{}, 1),
|
||||
newConnCh: make(chan *conn),
|
||||
bw: NewBandwidth(fd),
|
||||
IsClose: false,
|
||||
connType: connType,
|
||||
pingCh: make(chan []byte),
|
||||
pingCheckThreshold: checkThreshold,
|
||||
@@ -86,8 +85,11 @@ func NewMux(c net.Conn, connType string, pingCheckThreshold int) *Mux {
|
||||
return m
|
||||
}
|
||||
|
||||
// IsClose returns whether the mux connection has been closed.
|
||||
func (s *Mux) IsClose() bool { return s.isClose.Load() }
|
||||
|
||||
func (s *Mux) NewConn() (*conn, error) {
|
||||
if s.IsClose {
|
||||
if s.isClose.Load() {
|
||||
return nil, errors.New("the mux has closed")
|
||||
}
|
||||
conn := NewConn(s.getId(), s)
|
||||
@@ -106,7 +108,7 @@ func (s *Mux) NewConn() (*conn, error) {
|
||||
}
|
||||
|
||||
func (s *Mux) Accept() (net.Conn, error) {
|
||||
if s.IsClose {
|
||||
if s.isClose.Load() {
|
||||
return nil, errors.New("accpet error,the mux has closed")
|
||||
}
|
||||
conn := <-s.newConnCh
|
||||
@@ -121,7 +123,7 @@ func (s *Mux) Addr() net.Addr {
|
||||
}
|
||||
|
||||
func (s *Mux) sendInfo(flag uint8, id int32, data interface{}) {
|
||||
if s.IsClose {
|
||||
if s.isClose.Load() {
|
||||
return
|
||||
}
|
||||
var err error
|
||||
@@ -140,11 +142,11 @@ func (s *Mux) sendInfo(flag uint8, id int32, data interface{}) {
|
||||
func (s *Mux) writeSession() {
|
||||
go func() {
|
||||
for {
|
||||
if s.IsClose {
|
||||
if s.isClose.Load() {
|
||||
break
|
||||
}
|
||||
pack := s.writeQueue.Pop()
|
||||
if s.IsClose {
|
||||
if s.isClose.Load() {
|
||||
break
|
||||
}
|
||||
//if pack.flag == muxNewMsg || pack.flag == muxNewMsgPart {
|
||||
@@ -173,7 +175,7 @@ func (s *Mux) ping() {
|
||||
ticker := time.NewTicker(time.Second * 5)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
if s.IsClose {
|
||||
if s.isClose.Load() {
|
||||
break
|
||||
}
|
||||
select {
|
||||
@@ -197,7 +199,7 @@ func (s *Mux) ping() {
|
||||
var now time.Time
|
||||
var data []byte
|
||||
for {
|
||||
if s.IsClose {
|
||||
if s.isClose.Load() {
|
||||
break
|
||||
}
|
||||
select {
|
||||
@@ -213,7 +215,7 @@ func (s *Mux) ping() {
|
||||
// convert float64 to bits, store it atomic
|
||||
//log.Println("ping", math.Float64frombits(atomic.LoadUint64(&s.latency)))
|
||||
}
|
||||
if cap(data) > 0 && !s.IsClose {
|
||||
if cap(data) > 0 && !s.isClose.Load() {
|
||||
windowBuff.Put(data)
|
||||
}
|
||||
}
|
||||
@@ -224,11 +226,11 @@ func (s *Mux) readSession() {
|
||||
go func() {
|
||||
var connection *conn
|
||||
for {
|
||||
if s.IsClose {
|
||||
if s.isClose.Load() {
|
||||
break
|
||||
}
|
||||
connection = s.newConnQueue.Pop()
|
||||
if s.IsClose {
|
||||
if s.isClose.Load() {
|
||||
break // make sure that is closed
|
||||
}
|
||||
s.connMap.Set(connection.connId, connection) //it has been Set before send ok
|
||||
@@ -241,7 +243,7 @@ func (s *Mux) readSession() {
|
||||
var l uint16
|
||||
var err error
|
||||
for {
|
||||
if s.IsClose {
|
||||
if s.isClose.Load() {
|
||||
return
|
||||
}
|
||||
pack = muxPack.Get()
|
||||
@@ -322,10 +324,10 @@ func (s *Mux) newMsg(connection *conn, pack *muxPackager) (err error) {
|
||||
}
|
||||
|
||||
func (s *Mux) Close() (err error) {
|
||||
if s.IsClose {
|
||||
if s.isClose.Load() {
|
||||
return errors.New("the mux has closed")
|
||||
}
|
||||
s.IsClose = true
|
||||
s.isClose.Store(true)
|
||||
log.Println("close mux")
|
||||
s.connMap.Close()
|
||||
//s.connMap = nil
|
||||
@@ -361,7 +363,7 @@ func (s *Mux) release() {
|
||||
s.newConnQueue.Stop()
|
||||
}
|
||||
|
||||
//Get New connId as unique flag
|
||||
// Get New connId as unique flag
|
||||
func (s *Mux) getId() (id int32) {
|
||||
//Avoid going beyond the scope
|
||||
if (math.MaxInt32 - s.id) < 10000 {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package version
|
||||
|
||||
const VERSION = "0.26.33"
|
||||
const VERSION = "0.26.34"
|
||||
|
||||
// Compulsory minimum version, Minimum downward compatibility to this version
|
||||
func GetVersion() string {
|
||||
|
||||
@@ -345,7 +345,7 @@ func GetServerNameFromClientHello(c net.Conn) (string, []byte) {
|
||||
return "", header
|
||||
}
|
||||
recordLen := int(header[3])<<8 | int(header[4])
|
||||
if recordLen <= 0 {
|
||||
if recordLen <= 0 || recordLen > 16384 {
|
||||
return "", header
|
||||
}
|
||||
|
||||
|
||||
+67
-13
@@ -108,22 +108,47 @@ func (s *Sock5ModeServer) sendReply(c net.Conn, rep uint8) {
|
||||
// do conn
|
||||
func (s *Sock5ModeServer) doConnect(c net.Conn, command uint8) {
|
||||
addrType := make([]byte, 1)
|
||||
c.Read(addrType)
|
||||
if _, err := io.ReadFull(c, addrType); err != nil {
|
||||
logs.Warn("read addr type error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
var host string
|
||||
switch addrType[0] {
|
||||
case ipV4:
|
||||
ipv4 := make(net.IP, net.IPv4len)
|
||||
c.Read(ipv4)
|
||||
if _, err := io.ReadFull(c, ipv4); err != nil {
|
||||
logs.Warn("read ipv4 error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
host = ipv4.String()
|
||||
case ipV6:
|
||||
ipv6 := make(net.IP, net.IPv6len)
|
||||
c.Read(ipv6)
|
||||
if _, err := io.ReadFull(c, ipv6); err != nil {
|
||||
logs.Warn("read ipv6 error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
host = ipv6.String()
|
||||
case domainName:
|
||||
var domainLen uint8
|
||||
binary.Read(c, binary.BigEndian, &domainLen)
|
||||
if err := binary.Read(c, binary.BigEndian, &domainLen); err != nil {
|
||||
logs.Warn("read domain len error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
domain := make([]byte, domainLen)
|
||||
c.Read(domain)
|
||||
if _, err := io.ReadFull(c, domain); err != nil {
|
||||
logs.Warn("read domain error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
host = string(domain)
|
||||
default:
|
||||
s.sendReply(c, addrTypeNotSupported)
|
||||
@@ -131,7 +156,12 @@ func (s *Sock5ModeServer) doConnect(c net.Conn, command uint8) {
|
||||
}
|
||||
|
||||
var port uint16
|
||||
binary.Read(c, binary.BigEndian, &port)
|
||||
if err := binary.Read(c, binary.BigEndian, &port); err != nil {
|
||||
logs.Warn("read port error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
// connect to host
|
||||
addr := net.JoinHostPort(host, strconv.Itoa(int(port)))
|
||||
var ltype string
|
||||
@@ -176,22 +206,42 @@ func (s *Sock5ModeServer) sendUdpReply(writeConn net.Conn, c net.Conn, rep uint8
|
||||
func (s *Sock5ModeServer) handleUDP(c net.Conn) {
|
||||
defer c.Close()
|
||||
addrType := make([]byte, 1)
|
||||
c.Read(addrType)
|
||||
if _, err := io.ReadFull(c, addrType); err != nil {
|
||||
logs.Warn("read addr type error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
return
|
||||
}
|
||||
var host string
|
||||
switch addrType[0] {
|
||||
case ipV4:
|
||||
ipv4 := make(net.IP, net.IPv4len)
|
||||
c.Read(ipv4)
|
||||
if _, err := io.ReadFull(c, ipv4); err != nil {
|
||||
logs.Warn("read ipv4 error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
return
|
||||
}
|
||||
host = ipv4.String()
|
||||
case ipV6:
|
||||
ipv6 := make(net.IP, net.IPv6len)
|
||||
c.Read(ipv6)
|
||||
if _, err := io.ReadFull(c, ipv6); err != nil {
|
||||
logs.Warn("read ipv6 error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
return
|
||||
}
|
||||
host = ipv6.String()
|
||||
case domainName:
|
||||
var domainLen uint8
|
||||
binary.Read(c, binary.BigEndian, &domainLen)
|
||||
if err := binary.Read(c, binary.BigEndian, &domainLen); err != nil {
|
||||
logs.Warn("read domain len error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
return
|
||||
}
|
||||
domain := make([]byte, domainLen)
|
||||
c.Read(domain)
|
||||
if _, err := io.ReadFull(c, domain); err != nil {
|
||||
logs.Warn("read domain error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
return
|
||||
}
|
||||
host = string(domain)
|
||||
default:
|
||||
s.sendReply(c, addrTypeNotSupported)
|
||||
@@ -199,8 +249,12 @@ func (s *Sock5ModeServer) handleUDP(c net.Conn) {
|
||||
}
|
||||
//读取端口
|
||||
var port uint16
|
||||
binary.Read(c, binary.BigEndian, &port)
|
||||
logs.Warn(host, string(port))
|
||||
if err := binary.Read(c, binary.BigEndian, &port); err != nil {
|
||||
logs.Warn("read port error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
return
|
||||
}
|
||||
logs.Warn(host, strconv.Itoa(int(port)))
|
||||
replyAddr, err := net.ResolveUDPAddr("udp", s.task.ServerIp+":0")
|
||||
if err != nil {
|
||||
logs.Error("build local reply addr error", err)
|
||||
|
||||
+42
-46
@@ -87,6 +87,12 @@ func DealBridgeTask() {
|
||||
// start a new server
|
||||
func StartNewServer(bridgePort int, cnf *file.Tunnel, bridgeType string, bridgeDisconnect int) {
|
||||
Bridge = bridge.NewTunnel(bridgePort, bridgeType, common.GetBoolByStr(beego.AppConfig.String("ip_limit")), RunList, bridgeDisconnect)
|
||||
// 启动流量持久化(只启动一次,避免每次 AddTask 创建泄漏的 goroutine)
|
||||
if minute, err := beego.AppConfig.Int("flow_store_interval"); err == nil && minute > 0 {
|
||||
go flowSession(time.Minute * time.Duration(minute))
|
||||
}
|
||||
// 启动后台 IO 速率采集,Dashboard 直接读缓存,无需 Sleep
|
||||
tool.StartIORateCollector()
|
||||
go func() {
|
||||
if err := Bridge.StartTunnel(); err != nil {
|
||||
logs.Error("start server bridge error", err)
|
||||
@@ -189,9 +195,6 @@ func AddTask(t *file.Tunnel) error {
|
||||
logs.Error("taskId %d start error port %d open failed", t.Id, t.Port)
|
||||
return errors.New("the port open error")
|
||||
}
|
||||
if minute, err := beego.AppConfig.Int("flow_store_interval"); err == nil && minute > 0 {
|
||||
go flowSession(time.Minute * time.Duration(minute))
|
||||
}
|
||||
if svr := NewMode(Bridge, t); svr != nil {
|
||||
logs.Info("tunnel task %s start mode:%s port %d", t.Remark, t.Mode, t.Port)
|
||||
//RunList[t.Id] = svr
|
||||
@@ -238,18 +241,16 @@ func GetTunnel(start, length int, typeVal string, clientId int, search string, s
|
||||
all_list := make([]*file.Tunnel, 0) //store all Tunnel
|
||||
list := make([]*file.Tunnel, 0)
|
||||
var cnt int
|
||||
keys := file.GetMapKeys(file.GetDb().JsonDb.Tasks, false, "", "")
|
||||
|
||||
//get all Tunnel and sort
|
||||
for _, key := range keys {
|
||||
if value, ok := file.GetDb().JsonDb.Tasks.Load(key); ok {
|
||||
v := value.(*file.Tunnel)
|
||||
if (typeVal != "" && v.Mode != typeVal || (clientId != 0 && v.Client.Id != clientId)) || (typeVal == "" && clientId != v.Client.Id) {
|
||||
continue
|
||||
}
|
||||
all_list = append(all_list, v)
|
||||
// 单次遍历收集所有符合条件的 Tunnel(修复原代码双重遍历 sync.Map 的性能问题)
|
||||
file.GetDb().JsonDb.Tasks.Range(func(key, value interface{}) bool {
|
||||
v := value.(*file.Tunnel)
|
||||
if (typeVal != "" && v.Mode != typeVal || (clientId != 0 && v.Client.Id != clientId)) || (typeVal == "" && clientId != v.Client.Id) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
all_list = append(all_list, v)
|
||||
return true
|
||||
})
|
||||
//sort by Id, Remark, TargetStr, Port, asc or desc
|
||||
if sortField == "Id" {
|
||||
if order == "asc" {
|
||||
@@ -283,31 +284,25 @@ func GetTunnel(start, length int, typeVal string, clientId int, search string, s
|
||||
}
|
||||
}
|
||||
|
||||
//search
|
||||
for _, key := range all_list {
|
||||
if value, ok := file.GetDb().JsonDb.Tasks.Load(key.Id); ok {
|
||||
v := value.(*file.Tunnel)
|
||||
if (typeVal != "" && v.Mode != typeVal || (clientId != 0 && v.Client.Id != clientId)) || (typeVal == "" && clientId != v.Client.Id) {
|
||||
continue
|
||||
}
|
||||
if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || v.Port == common.GetIntNoErrByStr(search) || strings.Contains(v.Password, search) || strings.Contains(v.Remark, search) || strings.Contains(v.Target.TargetStr, search)) {
|
||||
continue
|
||||
}
|
||||
cnt++
|
||||
if _, ok := Bridge.Client.Load(v.Client.Id); ok {
|
||||
v.Client.IsConnect = true
|
||||
} else {
|
||||
v.Client.IsConnect = false
|
||||
}
|
||||
if start--; start < 0 {
|
||||
if length--; length >= 0 {
|
||||
if _, ok := RunList.Load(v.Id); ok {
|
||||
v.RunStatus = true
|
||||
} else {
|
||||
v.RunStatus = false
|
||||
}
|
||||
list = append(list, v)
|
||||
//search and paginate(直接在已排序的列表上操作,避免二次 Load)
|
||||
for _, v := range all_list {
|
||||
if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || v.Port == common.GetIntNoErrByStr(search) || strings.Contains(v.Password, search) || strings.Contains(v.Remark, search) || strings.Contains(v.Target.TargetStr, search)) {
|
||||
continue
|
||||
}
|
||||
cnt++
|
||||
if _, ok := Bridge.Client.Load(v.Client.Id); ok {
|
||||
v.Client.IsConnect = true
|
||||
} else {
|
||||
v.Client.IsConnect = false
|
||||
}
|
||||
if start--; start < 0 {
|
||||
if length--; length >= 0 {
|
||||
if _, ok := RunList.Load(v.Id); ok {
|
||||
v.RunStatus = true
|
||||
} else {
|
||||
v.RunStatus = false
|
||||
}
|
||||
list = append(list, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -450,25 +445,26 @@ func GetDashboardData() map[string]interface{} {
|
||||
data["swap_mem"] = math.Round(swap.UsedPercent)
|
||||
vir, _ := mem.VirtualMemory()
|
||||
data["virtual_mem"] = math.Round(vir.UsedPercent)
|
||||
conn, _ := net.ProtoCounters(nil)
|
||||
io1, _ := net.IOCounters(false)
|
||||
time.Sleep(time.Millisecond * 500)
|
||||
io2, _ := net.IOCounters(false)
|
||||
if len(io2) > 0 && len(io1) > 0 {
|
||||
data["io_send"] = (io2[0].BytesSent - io1[0].BytesSent) * 2
|
||||
data["io_recv"] = (io2[0].BytesRecv - io1[0].BytesRecv) * 2
|
||||
// IO 速率从后台缓存读取,无需 Sleep 500ms
|
||||
if cached, ok := tool.IORateCache.Load().(map[string]uint64); ok {
|
||||
data["io_send"] = cached["io_send"]
|
||||
data["io_recv"] = cached["io_recv"]
|
||||
}
|
||||
conn, _ := net.ProtoCounters(nil)
|
||||
for _, v := range conn {
|
||||
data[v.Protocol] = v.Stats["CurrEstab"]
|
||||
}
|
||||
//chart
|
||||
var fg int
|
||||
if len(tool.ServerStatus) >= 10 {
|
||||
fg = len(tool.ServerStatus) / 10
|
||||
tool.ServerStatusMu.RLock()
|
||||
statusLen := len(tool.ServerStatus)
|
||||
if statusLen >= 10 {
|
||||
fg = statusLen / 10
|
||||
for i := 0; i <= 9; i++ {
|
||||
data["sys"+strconv.Itoa(i+1)] = tool.ServerStatus[i*fg]
|
||||
}
|
||||
}
|
||||
tool.ServerStatusMu.RUnlock()
|
||||
return data
|
||||
}
|
||||
|
||||
|
||||
+59
-9
@@ -4,6 +4,8 @@ import (
|
||||
"math"
|
||||
"math/rand"
|
||||
"strconv"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"ehang.io/nps/lib/common"
|
||||
@@ -15,8 +17,10 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
ports []int
|
||||
ServerStatus []map[string]interface{}
|
||||
ports []int
|
||||
ServerStatus []map[string]interface{}
|
||||
ServerStatusMu sync.RWMutex
|
||||
IORateCache atomic.Value
|
||||
)
|
||||
|
||||
func StartSystemInfo() {
|
||||
@@ -52,7 +56,7 @@ func TestServerPort(p int, m string) (b bool) {
|
||||
}
|
||||
|
||||
func GenerateServerPort(m string) int {
|
||||
for {
|
||||
for i := 0; i < 1000; i++ {
|
||||
//生成随机数 1024 - 65535
|
||||
serverPort := rand.Intn(65535)
|
||||
if serverPort < 1024 {
|
||||
@@ -63,6 +67,7 @@ func GenerateServerPort(m string) int {
|
||||
return serverPort
|
||||
}
|
||||
}
|
||||
return 0 // 超过最大重试次数,返回0表示无法分配端口
|
||||
}
|
||||
|
||||
func getSeverStatus() {
|
||||
@@ -88,12 +93,9 @@ func getSeverStatus() {
|
||||
vir, _ := mem.VirtualMemory()
|
||||
m["virtual_mem"] = math.Round(vir.UsedPercent)
|
||||
conn, _ := net.ProtoCounters(nil)
|
||||
io1, _ := net.IOCounters(false)
|
||||
time.Sleep(time.Millisecond * 500)
|
||||
io2, _ := net.IOCounters(false)
|
||||
if len(io2) > 0 && len(io1) > 0 {
|
||||
m["io_send"] = (io2[0].BytesSent - io1[0].BytesSent) * 2
|
||||
m["io_recv"] = (io2[0].BytesRecv - io1[0].BytesRecv) * 2
|
||||
if cached, ok := IORateCache.Load().(map[string]uint64); ok {
|
||||
m["io_send"] = cached["io_send"]
|
||||
m["io_recv"] = cached["io_recv"]
|
||||
}
|
||||
t := time.Now()
|
||||
m["time"] = strconv.Itoa(t.Hour()) + ":" + strconv.Itoa(t.Minute()) + ":" + strconv.Itoa(t.Second())
|
||||
@@ -102,8 +104,56 @@ func getSeverStatus() {
|
||||
m[v.Protocol] = v.Stats["CurrEstab"]
|
||||
}
|
||||
if len(ServerStatus) >= 1440 {
|
||||
ServerStatusMu.Lock()
|
||||
ServerStatus = ServerStatus[1:]
|
||||
ServerStatusMu.Unlock()
|
||||
}
|
||||
ServerStatusMu.Lock()
|
||||
ServerStatus = append(ServerStatus, m)
|
||||
ServerStatusMu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// StartIORateCollector 启动后台 IO 速率采集,每 2s 刷新一次 IORateCache
|
||||
func StartIORateCollector() {
|
||||
go collectIORate()
|
||||
}
|
||||
|
||||
func collectIORate() {
|
||||
var lastSent, lastRecv uint64
|
||||
// 修复:无论首次 IOCounters 是否成功,都把 lastTime 设为 now,
|
||||
// 否则首次有效采样的 elapsed 会是几十年,导致 sendRate/recvRate 直接为 0
|
||||
lastTime := time.Now()
|
||||
if io, err := net.IOCounters(false); err == nil && len(io) > 0 {
|
||||
lastSent = io[0].BytesSent
|
||||
lastRecv = io[0].BytesRecv
|
||||
}
|
||||
|
||||
ticker := time.NewTicker(2 * time.Second)
|
||||
defer ticker.Stop()
|
||||
for range ticker.C {
|
||||
now := time.Now()
|
||||
io, err := net.IOCounters(false)
|
||||
if err != nil || len(io) == 0 {
|
||||
continue
|
||||
}
|
||||
elapsed := now.Sub(lastTime).Seconds()
|
||||
if elapsed <= 0 {
|
||||
continue
|
||||
}
|
||||
var sendRate, recvRate uint64
|
||||
if io[0].BytesSent >= lastSent {
|
||||
sendRate = uint64(float64(io[0].BytesSent-lastSent) / elapsed)
|
||||
}
|
||||
if io[0].BytesRecv >= lastRecv {
|
||||
recvRate = uint64(float64(io[0].BytesRecv-lastRecv) / elapsed)
|
||||
}
|
||||
lastSent = io[0].BytesSent
|
||||
lastRecv = io[0].BytesRecv
|
||||
lastTime = now
|
||||
IORateCache.Store(map[string]uint64{
|
||||
"io_send": sendRate,
|
||||
"io_recv": recvRate,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user