dht_net.go 5.45 KB
Newer Older
1 2 3
package dht

import (
4
	"fmt"
5
	"sync"
6 7
	"time"

8 9 10
	ggio "github.com/gogo/protobuf/io"
	peer "github.com/ipfs/go-libp2p-peer"
	ctxio "github.com/jbenet/go-context/io"
George Antoniadis's avatar
George Antoniadis committed
11
	inet "github.com/libp2p/go-libp2p/p2p/net"
12
	context "golang.org/x/net/context"
George Antoniadis's avatar
George Antoniadis committed
13 14

	pb "github.com/libp2p/go-libp2p-kad-dht/pb"
15 16
)

17 18 19
var dhtReadMessageTimeout = time.Minute
var ErrReadTimeout = fmt.Errorf("timed out reading response")

20 21 22 23 24 25 26 27 28
// handleNewStream implements the inet.StreamHandler
func (dht *IpfsDHT) handleNewStream(s inet.Stream) {
	go dht.handleNewMessage(s)
}

func (dht *IpfsDHT) handleNewMessage(s inet.Stream) {
	defer s.Close()

	ctx := dht.Context()
29 30
	cr := ctxio.NewReader(ctx, s) // ok to use. we defer close stream in this func
	cw := ctxio.NewWriter(ctx, s) // ok to use. we defer close stream in this func
31 32
	r := ggio.NewDelimitedReader(cr, inet.MessageSizeMax)
	w := ggio.NewDelimitedWriter(cw)
33 34
	mPeer := s.Conn().RemotePeer()

35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
	for {
		// receive msg
		pmes := new(pb.Message)
		if err := r.ReadMsg(pmes); err != nil {
			log.Debugf("Error unmarshaling data: %s", err)
			return
		}

		// update the peer (on valid msgs only)
		dht.updateFromMessage(ctx, mPeer, pmes)

		// get handler for this msg type.
		handler := dht.handlerForMsgType(pmes.GetType())
		if handler == nil {
			log.Debug("got back nil handler from handlerForMsgType")
			return
		}

		// dispatch handler.
		rpmes, err := handler(ctx, mPeer, pmes)
		if err != nil {
			log.Debugf("handle message error: %s", err)
			return
		}

		// if nil response, return it before serializing
		if rpmes == nil {
62
			log.Debug("got back nil response from request")
63 64 65 66 67 68 69 70
			continue
		}

		// send out response msg
		if err := w.WriteMsg(rpmes); err != nil {
			log.Debugf("send response error: %s", err)
			return
		}
71 72 73 74 75
	}
}

// sendRequest sends out a request, but also makes sure to
// measure the RTT for latency measurements.
76
func (dht *IpfsDHT) sendRequest(ctx context.Context, p peer.ID, pmes *pb.Message) (*pb.Message, error) {
77

78
	ms := dht.messageSenderForPeer(p)
79 80 81

	start := time.Now()

82 83
	rpmes, err := ms.SendRequest(ctx, pmes)
	if err != nil {
84 85 86
		return nil, err
	}

87 88 89
	// update the peer (on valid msgs only)
	dht.updateFromMessage(ctx, p, rpmes)

90
	dht.peerstore.RecordLatency(p, time.Since(start))
91 92 93
	log.Event(ctx, "dhtReceivedMessage", dht.self, p, rpmes)
	return rpmes, nil
}
94 95

// sendMessage sends out a message
96
func (dht *IpfsDHT) sendMessage(ctx context.Context, p peer.ID, pmes *pb.Message) error {
97

98
	ms := dht.messageSenderForPeer(p)
99

100
	if err := ms.SendMessage(ctx, pmes); err != nil {
101 102 103 104 105
		return err
	}
	log.Event(ctx, "dhtSentMessage", dht.self, p, pmes)
	return nil
}
106 107 108 109 110

func (dht *IpfsDHT) updateFromMessage(ctx context.Context, p peer.ID, mes *pb.Message) error {
	dht.Update(ctx, p)
	return nil
}
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131

func (dht *IpfsDHT) messageSenderForPeer(p peer.ID) *messageSender {
	dht.smlk.Lock()
	defer dht.smlk.Unlock()

	ms, ok := dht.strmap[p]
	if !ok {
		ms = dht.newMessageSender(p)
		dht.strmap[p] = ms
	}

	return ms
}

type messageSender struct {
	s   inet.Stream
	r   ggio.ReadCloser
	w   ggio.WriteCloser
	lk  sync.Mutex
	p   peer.ID
	dht *IpfsDHT
Jeromy's avatar
Jeromy committed
132 133

	singleMes int
134 135 136 137 138 139 140 141 142 143 144
}

func (dht *IpfsDHT) newMessageSender(p peer.ID) *messageSender {
	return &messageSender{p: p, dht: dht}
}

func (ms *messageSender) prep() error {
	if ms.s != nil {
		return nil
	}

George Antoniadis's avatar
George Antoniadis committed
145
	nstr, err := ms.dht.host.NewStream(ms.dht.ctx, ms.p, ProtocolDHT)
146 147 148 149
	if err != nil {
		return err
	}

150 151 152 153 154 155 156
	ms.r = ggio.NewDelimitedReader(nstr, inet.MessageSizeMax)
	ms.w = ggio.NewDelimitedWriter(nstr)
	ms.s = nstr

	return nil
}

157 158 159 160
// streamReuseTries is the number of times we will try to reuse a stream to a
// given peer before giving up and reverting to the old one-message-per-stream
// behaviour.
const streamReuseTries = 3
161

162 163 164 165
func (ms *messageSender) SendMessage(ctx context.Context, pmes *pb.Message) error {
	ms.lk.Lock()
	defer ms.lk.Unlock()
	if err := ms.prep(); err != nil {
166 167
		return err
	}
168

Jeromy's avatar
Jeromy committed
169 170 171 172
	if err := ms.writeMessage(pmes); err != nil {
		return err
	}

173
	if ms.singleMes > streamReuseTries {
Jeromy's avatar
Jeromy committed
174 175 176 177
		ms.s.Close()
		ms.s = nil
	}

178 179
	return nil
}
180

Jeromy's avatar
Jeromy committed
181
func (ms *messageSender) writeMessage(pmes *pb.Message) error {
182 183
	err := ms.w.WriteMsg(pmes)
	if err != nil {
Jeromy's avatar
Jeromy committed
184 185 186 187 188
		// If the other side isnt expecting us to be reusing streams, we're gonna
		// end up erroring here. To make sure things work seamlessly, lets retry once
		// before continuing

		log.Infof("error writing message: ", err)
189 190
		ms.s.Close()
		ms.s = nil
Jeromy's avatar
Jeromy committed
191 192 193 194 195 196 197 198 199 200 201
		if err := ms.prep(); err != nil {
			return err
		}

		if err := ms.w.WriteMsg(pmes); err != nil {
			return err
		}

		// keep track of this happening. If it happens a few times, its
		// likely we can assume the otherside will never support stream reuse
		ms.singleMes++
202
	}
203 204
	return nil
}
205 206 207 208 209 210 211 212

func (ms *messageSender) SendRequest(ctx context.Context, pmes *pb.Message) (*pb.Message, error) {
	ms.lk.Lock()
	defer ms.lk.Unlock()
	if err := ms.prep(); err != nil {
		return nil, err
	}

Jeromy's avatar
Jeromy committed
213
	if err := ms.writeMessage(pmes); err != nil {
214 215 216 217 218 219
		return nil, err
	}

	log.Event(ctx, "dhtSentMessage", ms.dht.self, ms.p, pmes)

	mes := new(pb.Message)
220
	if err := ms.ctxReadMsg(ctx, mes); err != nil {
221 222 223 224 225
		ms.s.Close()
		ms.s = nil
		return nil, err
	}

226
	if ms.singleMes > streamReuseTries {
Jeromy's avatar
Jeromy committed
227 228 229 230
		ms.s.Close()
		ms.s = nil
	}

231 232
	return mes, nil
}
233 234 235

func (ms *messageSender) ctxReadMsg(ctx context.Context, mes *pb.Message) error {
	errc := make(chan error, 1)
236 237 238
	go func(r ggio.ReadCloser) {
		errc <- r.ReadMsg(mes)
	}(ms.r)
239

240 241 242
	t := time.NewTimer(dhtReadMessageTimeout)
	defer t.Stop()

243 244 245 246 247
	select {
	case err := <-errc:
		return err
	case <-ctx.Done():
		return ctx.Err()
248 249
	case <-t.C:
		return ErrReadTimeout
250 251
	}
}