2019-10-27 21:44:07 +08:00
|
|
|
package tunnel
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
2020-09-02 16:34:12 +08:00
|
|
|
"sync/atomic"
|
2019-10-27 21:44:07 +08:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
var DefaultManager *Manager
|
|
|
|
|
|
|
|
func init() {
|
2020-09-02 16:34:12 +08:00
|
|
|
DefaultManager = &Manager{}
|
2020-09-03 10:30:18 +08:00
|
|
|
|
|
|
|
go DefaultManager.handle()
|
2019-10-27 21:44:07 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
type Manager struct {
|
|
|
|
connections sync.Map
|
|
|
|
uploadTemp int64
|
|
|
|
downloadTemp int64
|
|
|
|
uploadBlip int64
|
|
|
|
downloadBlip int64
|
|
|
|
uploadTotal int64
|
|
|
|
downloadTotal int64
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *Manager) Join(c tracker) {
|
|
|
|
m.connections.Store(c.ID(), c)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *Manager) Leave(c tracker) {
|
|
|
|
m.connections.Delete(c.ID())
|
|
|
|
}
|
|
|
|
|
2020-09-02 16:34:12 +08:00
|
|
|
func (m *Manager) PushUploaded(size int64) {
|
|
|
|
atomic.AddInt64(&m.uploadTemp, size)
|
|
|
|
atomic.AddInt64(&m.uploadTotal, size)
|
2019-10-27 21:44:07 +08:00
|
|
|
}
|
|
|
|
|
2020-09-02 16:34:12 +08:00
|
|
|
func (m *Manager) PushDownloaded(size int64) {
|
|
|
|
atomic.AddInt64(&m.downloadTemp, size)
|
|
|
|
atomic.AddInt64(&m.downloadTotal, size)
|
2019-10-27 21:44:07 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (m *Manager) Now() (up int64, down int64) {
|
2020-09-02 16:34:12 +08:00
|
|
|
return atomic.LoadInt64(&m.uploadBlip), atomic.LoadInt64(&m.downloadBlip)
|
2019-10-27 21:44:07 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (m *Manager) Snapshot() *Snapshot {
|
|
|
|
connections := []tracker{}
|
|
|
|
m.connections.Range(func(key, value interface{}) bool {
|
|
|
|
connections = append(connections, value.(tracker))
|
|
|
|
return true
|
|
|
|
})
|
|
|
|
|
|
|
|
return &Snapshot{
|
2020-09-02 16:34:12 +08:00
|
|
|
UploadTotal: atomic.LoadInt64(&m.uploadTotal),
|
|
|
|
DownloadTotal: atomic.LoadInt64(&m.downloadTotal),
|
2019-10-27 21:44:07 +08:00
|
|
|
Connections: connections,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-11 00:20:10 +08:00
|
|
|
func (m *Manager) ResetStatistic() {
|
|
|
|
m.uploadTemp = 0
|
|
|
|
m.uploadBlip = 0
|
|
|
|
m.uploadTotal = 0
|
|
|
|
m.downloadTemp = 0
|
|
|
|
m.downloadBlip = 0
|
|
|
|
m.downloadTotal = 0
|
|
|
|
}
|
|
|
|
|
2019-10-27 21:44:07 +08:00
|
|
|
func (m *Manager) handle() {
|
|
|
|
ticker := time.NewTicker(time.Second)
|
2020-09-02 16:34:12 +08:00
|
|
|
|
2020-09-03 10:30:18 +08:00
|
|
|
for range ticker.C {
|
|
|
|
atomic.StoreInt64(&m.uploadBlip, atomic.LoadInt64(&m.uploadTemp))
|
|
|
|
atomic.StoreInt64(&m.uploadTemp, 0)
|
|
|
|
atomic.StoreInt64(&m.downloadBlip, atomic.LoadInt64(&m.downloadTemp))
|
|
|
|
atomic.StoreInt64(&m.downloadTemp, 0)
|
2019-10-27 21:44:07 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type Snapshot struct {
|
|
|
|
DownloadTotal int64 `json:"downloadTotal"`
|
|
|
|
UploadTotal int64 `json:"uploadTotal"`
|
|
|
|
Connections []tracker `json:"connections"`
|
|
|
|
}
|