Connection Track Read/Write Map issue, implemented mutex around the map.

This commit is contained in:
Henry Camacho 2017-03-19 09:57:28 -05:00
parent 4696ec4ec2
commit 057ec00f82
1 changed files with 17 additions and 3 deletions

View File

@ -1,8 +1,11 @@
package genericlistener package genericlistener
import "net" import (
import "context" "context"
import "fmt" "fmt"
"net"
"sync"
)
//Track -- used to track connection + domain //Track -- used to track connection + domain
type Track struct { type Track struct {
@ -20,6 +23,7 @@ func NewTrack(conn net.Conn, domain string) (p *Track) {
//Tracking -- //Tracking --
type Tracking struct { type Tracking struct {
mutex *sync.Mutex
connections map[string]*Track connections map[string]*Track
register chan *Track register chan *Track
unregister chan net.Conn unregister chan net.Conn
@ -28,6 +32,7 @@ type Tracking struct {
//NewTracking -- Constructor //NewTracking -- Constructor
func NewTracking() (p *Tracking) { func NewTracking() (p *Tracking) {
p = new(Tracking) p = new(Tracking)
p.mutex = &sync.Mutex{}
p.connections = make(map[string]*Track) p.connections = make(map[string]*Track)
p.register = make(chan *Track) p.register = make(chan *Track)
p.unregister = make(chan net.Conn) p.unregister = make(chan net.Conn)
@ -46,18 +51,22 @@ func (p *Tracking) Run(ctx context.Context) {
return return
case connection := <-p.register: case connection := <-p.register:
p.mutex.Lock()
key := connection.conn.RemoteAddr().String() key := connection.conn.RemoteAddr().String()
loginfo.Println("register fired", key) loginfo.Println("register fired", key)
p.connections[key] = connection p.connections[key] = connection
p.list() p.list()
p.mutex.Unlock()
case connection := <-p.unregister: case connection := <-p.unregister:
p.mutex.Lock()
key := connection.RemoteAddr().String() key := connection.RemoteAddr().String()
loginfo.Println("unregister fired", key) loginfo.Println("unregister fired", key)
if _, ok := p.connections[key]; ok { if _, ok := p.connections[key]; ok {
delete(p.connections, key) delete(p.connections, key)
} }
p.list() p.list()
p.mutex.Unlock()
} }
} }
} }
@ -71,6 +80,11 @@ func (p *Tracking) list() {
//Lookup -- //Lookup --
// - get connection from key // - get connection from key
func (p *Tracking) Lookup(key string) (c *Track, err error) { func (p *Tracking) Lookup(key string) (c *Track, err error) {
defer func() {
p.mutex.Unlock()
}()
p.mutex.Lock()
if _, ok := p.connections[key]; ok { if _, ok := p.connections[key]; ok {
c = p.connections[key] c = p.connections[key]
} else { } else {