Skip to content

Commit

Permalink
Merge pull request #12 from keminar/todo
Browse files Browse the repository at this point in the history
fix tcpcopy stats
  • Loading branch information
keminar authored Dec 11, 2022
2 parents 04afb27 + fadb8a0 commit 229d4ca
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 38 deletions.
85 changes: 47 additions & 38 deletions proto/stats/counter.go
Original file line number Diff line number Diff line change
@@ -1,38 +1,47 @@
package stats

import (
"log"
"sync"
"sync/atomic"
"time"
)

type Counter struct {
access sync.RWMutex
name string
active int64 // 活跃时间, 判断计数器是否可以清理
minute int // 打印日志时间, 当前分钟数不再打印
value int64
}

func (c *Counter) Add(delta int64) int64 {
c.access.Lock()
defer c.access.Unlock()
tmp := atomic.AddInt64(&c.value, delta)

now := time.Now().Minute()
if now != c.minute {
// 打印上一分钟的上行下行字节数
if tmp > 1e6 {
log.Println(c.name, tmp/1e6, "MB")
} else if tmp > 1e3 {
log.Println(c.name, tmp/1e3, "KB")
} else {
log.Println(c.name, tmp, "Bytes")
}
c.minute = now
c.active = time.Now().Unix()
tmp = atomic.SwapInt64(&c.value, 0)
}
return tmp
}
package stats

import (
"log"
"runtime"
"sync"
"sync/atomic"
"time"
)

type Counter struct {
access sync.RWMutex
name string
active int64 // 活跃时间, 判断计数器是否可以清理
minute int // 打印日志时间, 当前分钟数不再打印
value int64
}

func (c *Counter) Add(delta int64) int64 {
defer func() {
if err := recover(); err != nil {
const size = 32 << 10
buf := make([]byte, size)
buf = buf[:runtime.Stack(buf, false)]
log.Printf("panic stats: %v\n%s", err, buf)
}
}()
c.access.Lock()
defer c.access.Unlock()
tmp := atomic.AddInt64(&c.value, delta)

now := time.Now().Minute()
if now != c.minute {
// 打印上一分钟的上行下行字节数
if tmp > 1e6 {
log.Println(c.name, tmp/1e6, "MB")
} else if tmp > 1e3 {
log.Println(c.name, tmp/1e3, "KB")
} else {
log.Println(c.name, tmp, "Bytes")
}
c.minute = now
c.active = time.Now().Unix()
tmp = atomic.SwapInt64(&c.value, 0)
}
return tmp
}
5 changes: 5 additions & 0 deletions proto/tcpcopy.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ func (that *tcpCopy) response() error {
that.req.DstPort = conf.RouterConfig.TcpCopy.Port

network, connAddr := tunnel.buildAddress("", that.req.DstIP, that.req.DstPort)
if connAddr == "" {
err = errors.New("target address is empty")
return err
}
tunnel.registerCounter("", that.req.DstIP, that.req.DstPort)
err = tunnel.dail(network, connAddr)
if err != nil {
log.Println(trace.ID(that.req.ID), "dail err", err.Error())
Expand Down

0 comments on commit 229d4ca

Please sign in to comment.