transx/stat/tunnelstatus.go

85 lines
1.8 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 {
mux sync.Mutex
tunnelList list.List
regChan chan interface{}
unregChan chan interface{}
}
func NewTunnelStatusManager() *TunnelStatusManager {
t := new(TunnelStatusManager)
t.regChan = make(chan interface{})
t.unregChan = make(chan interface{})
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{}) {
this.mux.Lock()
defer this.mux.Unlock()
this.tunnelList.PushBack(t)
}
func (this *TunnelStatusManager) unregister(t interface{}) {
this.mux.Lock()
defer this.mux.Unlock()
l := this.tunnelList
log.Debug("%d tunnels before remove.", this.tunnelList.Len())
n := 0
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 {
// log.Debug("Found")
// l.Remove(e)
// break
n++
nl.PushBack(e.Value)
2015-11-20 14:19:10 +08:00
}
}
if n == this.tunnelList.Len() {
m := t.(*model.Tunnel)
log.Debug("check tunntel %s", m.GetID())
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)
log.Debug("A tunnel registered")
log.Debug(this.QueryStatString())
2015-11-20 14:19:10 +08:00
case ur := <-this.unregChan:
this.unregister(ur)
log.Debug("A tunnel unregistered")
2015-11-20 14:19:10 +08:00
}
}
}
func (this *TunnelStatusManager) QueryStatString() string {
this.mux.Lock()
defer this.mux.Unlock()
return fmt.Sprintf("There %d tunnels running.\n", this.tunnelList.Len())
}