transx/stat/tunnelstatus.go

80 lines
1.7 KiB
Go
Raw Normal View History

2015-11-20 14:19:10 +08:00
package stat
import (
"container/list"
"fmt"
"github.com/TransX/log"
"github.com/TransX/model"
2015-11-20 14:19:10 +08:00
"sync"
)
type TunnelStatusManager struct {
2016-01-14 00:06:46 +08:00
mux sync.Mutex
tunnelList *list.List
2015-11-20 14:19:10 +08:00
regChan chan interface{}
unregChan chan interface{}
}
func NewTunnelStatusManager() *TunnelStatusManager {
t := new(TunnelStatusManager)
t.regChan = make(chan interface{})
t.unregChan = make(chan interface{})
t.tunnelList = new(list.List)
2015-11-20 14:19:10 +08:00
go t.chanListener()
return t
}
func (this *TunnelStatusManager) GetRegChan() chan interface{} {
return this.regChan
}
func (this *TunnelStatusManager) GetUnregChan() chan interface{} {
return this.unregChan
}
func (this *TunnelStatusManager) register(t interface{}) {
2016-01-14 00:06:46 +08:00
this.mux.Lock()
defer this.mux.Unlock()
2015-11-20 14:19:10 +08:00
this.tunnelList.PushBack(t)
}
func (this *TunnelStatusManager) unregister(t interface{}) {
2016-01-14 00:06:46 +08:00
this.mux.Lock()
defer this.mux.Unlock()
2015-11-20 14:19:10 +08:00
l := this.tunnelList
// log.Debug("%d tunnels before remove.", this.tunnelList.Len())
nl := new(list.List)
2015-11-20 14:19:10 +08:00
for e := l.Front(); e != nil; e = e.Next() {
if e.Value != t {
nl.PushBack(e.Value)
2015-11-20 14:19:10 +08:00
}
}
this.tunnelList = nl
// log.Debug("%d tunnels after remove.", this.tunnelList.Len())
2015-11-20 14:19:10 +08:00
}
func (this *TunnelStatusManager) chanListener() {
for {
select {
case r := <-this.regChan:
this.register(r)
m := r.(*model.Tunnel)
log.Debug("A tunnel registered id %s", m.GetID())
log.Debug(this.QueryStatString())
2015-11-20 14:19:10 +08:00
case ur := <-this.unregChan:
2015-11-20 14:19:10 +08:00
this.unregister(ur)
m := ur.(*model.Tunnel)
log.Debug("A tunnel unregistered id %s", m.GetID())
2015-11-20 14:19:10 +08:00
}
}
}
func (this *TunnelStatusManager) QueryStatString() string {
2016-01-14 00:06:46 +08:00
this.mux.Lock()
defer this.mux.Unlock()
2015-11-20 14:19:10 +08:00
return fmt.Sprintf("There %d tunnels running.\n", this.tunnelList.Len())
}