multiconn.go 6.09 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3 4 5 6 7 8 9 10
package conn

import (
	"sync"

	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
	ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"

	peer "github.com/jbenet/go-ipfs/peer"
	u "github.com/jbenet/go-ipfs/util"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
11
	ctxc "github.com/jbenet/go-ipfs/util/ctxcloser"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
12 13
)

14 15 16
// MultiConnMap is for shorthand
type MultiConnMap map[u.Key]*MultiConn

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
// Duplex is a simple duplex channel
type Duplex struct {
	In  chan []byte
	Out chan []byte
}

// MultiConn represents a single connection to another Peer (IPFS Node).
type MultiConn struct {

	// connections, mapped by a string, which uniquely identifies the connection.
	// this string is:  /addr1/peer1/addr2/peer2 (peers ordered lexicographically)
	conns map[string]Conn

	local  *peer.Peer
	remote *peer.Peer

	// fan-in/fan-out
	duplex Duplex

	// for adding/removing connections concurrently
	sync.RWMutex
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
38
	ctxc.ContextCloser
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
39 40 41
}

// NewMultiConn constructs a new connection
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
42
func NewMultiConn(ctx context.Context, local, remote *peer.Peer, conns []Conn) (*MultiConn, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
43 44 45 46 47 48 49 50 51 52 53 54

	c := &MultiConn{
		local:  local,
		remote: remote,
		conns:  map[string]Conn{},
		duplex: Duplex{
			In:  make(chan []byte, 10),
			Out: make(chan []byte, 10),
		},
	}

	// must happen before Adds / fanOut
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
55
	c.ContextCloser = ctxc.NewContextCloser(ctx, c.close)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72

	if conns != nil && len(conns) > 0 {
		c.Add(conns...)
	}
	go c.fanOut()
	return c, nil
}

// Add adds given Conn instances to multiconn.
func (c *MultiConn) Add(conns ...Conn) {
	c.Lock()
	defer c.Unlock()

	for _, c2 := range conns {
		log.Info("MultiConn: adding %s", c2)
		if c.LocalPeer() != c2.LocalPeer() || c.RemotePeer() != c2.RemotePeer() {
			log.Error("%s", c2)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
73 74 75
			c.Unlock() // ok to unlock (to log). panicing.
			log.Error("%s", c)
			c.Lock() // gotta relock to avoid lock panic from deferring.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
			panic("connection addresses mismatch")
		}

		c.conns[c2.ID()] = c2
		go c.fanInSingle(c2)
		log.Info("MultiConn: added %s", c2)
	}
}

// Remove removes given Conn instances from multiconn.
func (c *MultiConn) Remove(conns ...Conn) {

	// first remove them to avoid sending any more messages through it.
	{
		c.Lock()
		for _, c1 := range conns {
			c2, found := c.conns[c1.ID()]
			if !found {
				panic("Conn not in MultiConn")
			}
			if c1 != c2 {
				panic("different Conn objects for same id.")
			}

			delete(c.conns, c2.ID())
		}
		c.Unlock()
	}

	// close all in parallel, but wait for all to be done closing.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
106
	CloseConns(conns...)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
107 108 109 110
}

// CloseConns closes multiple connections in parallel, and waits for all
// to finish closing.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
111
func CloseConns(conns ...Conn) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
	var wg sync.WaitGroup
	for _, child := range conns {

		select {
		case <-child.Closed(): // if already closed, continue
			continue
		default:
		}

		wg.Add(1)
		go func(child Conn) {
			child.Close()
			wg.Done()
		}(child)
	}
	wg.Wait()
}

// fanOut is the multiplexor out -- it sends outgoing messages over the
// underlying single connections.
func (c *MultiConn) fanOut() {
	c.Children().Add(1)
	defer c.Children().Done()

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
136
	i := 0
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
137 138 139 140 141 142 143 144
	for {
		select {
		case <-c.Closing():
			return

		// send data out through our "best connection"
		case m, more := <-c.duplex.Out:
			if !more {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
145
				log.Info("%s out channel closed", c)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
146 147 148 149 150 151 152
				return
			}
			sc := c.BestConn()
			if sc == nil {
				// maybe this should be a logged error, not a panic.
				panic("sending out multiconn without any live connection")
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
153 154 155

			i++
			log.Info("%s sending (%d)", sc, i)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
156 157 158 159 160 161 162 163 164 165 166 167 168
			sc.Out() <- m
		}
	}
}

// fanInSingle is a multiplexor in -- it receives incoming messages over the
// underlying single connections.
func (c *MultiConn) fanInSingle(child Conn) {
	c.Children().Add(1)
	child.Children().Add(1) // yep, on the child too.

	// cleanup all data associated with this child Connection.
	defer func() {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
169 170
		log.Info("closing: %s", child)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
171 172 173
		// in case it still is in the map, remove it.
		c.Lock()
		delete(c.conns, child.ID())
174
		connLen := len(c.conns)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
175 176 177 178
		c.Unlock()

		c.Children().Done()
		child.Children().Done()
179 180 181 182

		if connLen == 0 {
			c.Close() // close self if all underlying children are gone?
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
183 184
	}()

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
185
	i := 0
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
186 187 188 189 190 191 192 193 194 195
	for {
		select {
		case <-c.Closing(): // multiconn closing
			return

		case <-child.Closing(): // child closing
			return

		case m, more := <-child.In(): // receiving data
			if !more {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
196
				log.Info("%s in channel closed", child)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
197 198
				return // closed
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
199 200
			i++
			log.Info("%s received (%d)", child, i)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
			c.duplex.In <- m
		}
	}
}

// close is the internal close function, called by ContextCloser.Close
func (c *MultiConn) close() error {
	log.Debug("%s closing Conn with %s", c.local, c.remote)

	// get connections
	c.RLock()
	conns := make([]Conn, 0, len(c.conns))
	for _, c := range c.conns {
		conns = append(conns, c)
	}
	c.RUnlock()

	// close underlying connections
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
219
	CloseConns(conns...)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
	return nil
}

// BestConn is the best connection in this MultiConn
func (c *MultiConn) BestConn() Conn {
	c.RLock()
	defer c.RUnlock()

	var id1 string
	var c1 Conn
	for id2, c2 := range c.conns {
		if id1 == "" || id1 < id2 {
			id1 = id2
			c1 = c2
		}
	}
	return c1
}

// ID is an identifier unique to this connection.
// In MultiConn, this is all the children IDs XORed together.
func (c *MultiConn) ID() string {
	c.RLock()
	defer c.RUnlock()

	ids := []byte(nil)
	for i := range c.conns {
		if ids == nil {
			ids = []byte(i)
		} else {
			ids = u.XOR(ids, []byte(i))
		}
	}

	return string(ids)
}

func (c *MultiConn) String() string {
	return String(c, "MultiConn")
}

// LocalMultiaddr is the Multiaddr on this side
func (c *MultiConn) LocalMultiaddr() ma.Multiaddr {
	return c.BestConn().LocalMultiaddr()
}

// RemoteMultiaddr is the Multiaddr on the remote side
func (c *MultiConn) RemoteMultiaddr() ma.Multiaddr {
	return c.BestConn().RemoteMultiaddr()
}

// LocalPeer is the Peer on this side
func (c *MultiConn) LocalPeer() *peer.Peer {
	return c.local
}

// RemotePeer is the Peer on the remote side
func (c *MultiConn) RemotePeer() *peer.Peer {
	return c.remote
}

// In returns a readable message channel
func (c *MultiConn) In() <-chan []byte {
	return c.duplex.In
}

// Out returns a writable message channel
func (c *MultiConn) Out() chan<- []byte {
	return c.duplex.Out
}