-
Notifications
You must be signed in to change notification settings - Fork 77
/
packetconn.go
316 lines (279 loc) · 8.46 KB
/
packetconn.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
package netceptor
import (
"context"
"fmt"
"net"
"reflect"
"sync"
"time"
"github.com/ansible/receptor/pkg/logger"
"github.com/ansible/receptor/pkg/utils"
)
type PacketConner interface {
SetHopsToLive(hopsToLive byte)
GetHopsToLive() byte
SubscribeUnreachable(doneChan chan struct{}) chan UnreachableNotification
ReadFrom(p []byte) (int, net.Addr, error)
WriteTo(p []byte, addr net.Addr) (n int, err error)
LocalAddr() net.Addr
Close() error
SetDeadline(t time.Time) error
SetReadDeadline(t time.Time) error
GetReadDeadline() time.Time
SetWriteDeadline(t time.Time) error
Cancel() *context.CancelFunc
LocalService() string
GetLogger() *logger.ReceptorLogger
StartUnreachable()
}
type NetcForPacketConn interface {
GetEphemeralService() string
AddNameHash(name string) uint64
AddLocalServiceAdvertisement(service string, connType byte, tags map[string]string)
SendMessageWithHopsToLive(fromService string, toNode string, toService string, data []byte, hopsToLive byte) error
RemoveLocalServiceAdvertisement(service string) error
GetLogger() *logger.ReceptorLogger
NodeID() string
GetNetworkName() string
GetListenerLock() *sync.RWMutex
GetListenerRegistry() map[string]*PacketConn
GetUnreachableBroker() *utils.Broker
MaxForwardingHops() byte
Context() context.Context
}
// PacketConn implements the net.PacketConn interface via the Receptor network.
type PacketConn struct {
s NetcForPacketConn
localService string
recvChan chan *MessageData
readDeadlineMutex sync.Mutex
readDeadline time.Time
advertise bool
adTags map[string]string
connType byte
hopsToLive byte
unreachableSubs *utils.Broker
context context.Context
cancel context.CancelFunc
}
func NewPacketConnWithConst(s NetcForPacketConn, service string, advertise bool, adtags map[string]string, connTypeDatagram byte) *PacketConn {
npc := &PacketConn{
s: s,
localService: service,
recvChan: make(chan *MessageData),
advertise: advertise,
adTags: adtags,
connType: connTypeDatagram,
hopsToLive: s.MaxForwardingHops(),
}
npc.StartUnreachable()
s.GetListenerRegistry()[service] = npc
return npc
}
func NewPacketConn(s NetcForPacketConn, service string, connTypeDatagram byte) *PacketConn {
return NewPacketConnWithConst(s, service, false, nil, connTypeDatagram)
}
// ListenPacket returns a datagram connection compatible with Go's net.PacketConn.
// If service is blank, generates and uses an ephemeral service name.
func (s *Netceptor) ListenPacket(service string) (PacketConner, error) {
if len(service) > 8 {
return nil, fmt.Errorf("service name %s too long", service)
}
if service == "" {
service = s.GetEphemeralService()
}
s.listenerLock.Lock()
defer s.listenerLock.Unlock()
_, isReserved := s.reservedServices[service]
_, isListening := s.listenerRegistry[service]
if isReserved || isListening {
return nil, fmt.Errorf("service %s is already listening", service)
}
_ = s.AddNameHash(service)
pc := NewPacketConn(s, service, ConnTypeDatagram)
return pc, nil
}
// ListenPacketAndAdvertise returns a datagram listener, and also broadcasts service
// advertisements to the Receptor network as long as the listener remains open.
func (s *Netceptor) ListenPacketAndAdvertise(service string, tags map[string]string) (PacketConner, error) {
if len(service) > 8 {
return nil, fmt.Errorf("service name %s too long", service)
}
if service == "" {
service = s.GetEphemeralService()
}
s.listenerLock.Lock()
defer s.listenerLock.Unlock()
_, isReserved := s.reservedServices[service]
_, isListening := s.listenerRegistry[service]
if isReserved || isListening {
return nil, fmt.Errorf("service %s is already listening and advertising", service)
}
pc := NewPacketConnWithConst(s, service, true, tags, ConnTypeDatagram)
s.AddLocalServiceAdvertisement(service, ConnTypeDatagram, tags)
return pc, nil
}
func (pc *PacketConn) Cancel() *context.CancelFunc {
return &pc.cancel
}
func (pc *PacketConn) GetLogger() *logger.ReceptorLogger {
return pc.s.GetLogger()
}
// startUnreachable starts monitoring the netceptor unreachable channel and forwarding relevant messages.
func (pc *PacketConn) StartUnreachable() {
pc.context, pc.cancel = context.WithCancel(pc.s.Context())
pc.unreachableSubs = utils.NewBroker(pc.context, reflect.TypeOf(UnreachableNotification{}))
iChan := pc.s.GetUnreachableBroker().Subscribe()
go func() {
<-pc.context.Done()
pc.s.GetUnreachableBroker().Unsubscribe(iChan)
}()
go func() {
for msgIf := range iChan {
msg, ok := msgIf.(UnreachableNotification)
if !ok {
continue
}
FromNode := msg.FromNode
FromService := msg.FromService
if FromNode == pc.s.NodeID() && FromService == pc.localService {
_ = pc.unreachableSubs.Publish(msg)
}
}
}()
}
// SubscribeUnreachable subscribes for unreachable messages relevant to this PacketConn.
func (pc *PacketConn) SubscribeUnreachable(doneChan chan struct{}) chan UnreachableNotification {
iChan := pc.unreachableSubs.Subscribe()
if iChan == nil {
return nil
}
uChan := make(chan UnreachableNotification)
// goroutine 1
// if doneChan is selected, this will unsubscribe the channel, which should
// eventually close out the go routine 2
go func() {
select {
case <-doneChan:
pc.unreachableSubs.Unsubscribe(iChan)
case <-pc.context.Done():
}
}()
// goroutine 2
// this will exit when either the broker closes iChan, or the broker
// returns via pc.context.Done()
go func() {
for {
msgIf, ok := <-iChan
if !ok {
close(uChan)
return
}
msg, ok := msgIf.(UnreachableNotification)
if !ok {
continue
}
uChan <- msg
}
}()
return uChan
}
// ReadFrom reads a packet from the network and returns its data and address.
func (pc *PacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
var m *MessageData
if pc.GetReadDeadline().IsZero() {
select {
case m = <-pc.recvChan:
case <-pc.context.Done():
return 0, nil, fmt.Errorf("connection context closed")
}
} else {
select {
case m = <-pc.recvChan:
case <-time.After(time.Until(pc.GetReadDeadline())):
return 0, nil, ErrTimeout
}
}
if m == nil {
return 0, nil, fmt.Errorf("connection closed")
}
nCopied := copy(p, m.Data)
fromAddr := Addr{
network: pc.s.GetNetworkName(),
node: m.FromNode,
service: m.FromService,
}
return nCopied, fromAddr, nil
}
// WriteTo writes a packet to an address on the network.
func (pc *PacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
ncaddr, ok := addr.(Addr)
if !ok {
return 0, fmt.Errorf("attempt to write to non-netceptor address")
}
err = pc.s.SendMessageWithHopsToLive(pc.localService, ncaddr.node, ncaddr.service, p, pc.hopsToLive)
if err != nil {
return 0, err
}
return len(p), nil
}
// SetHopsToLive sets the HopsToLive value for future outgoing packets on this connection.
func (pc *PacketConn) SetHopsToLive(hopsToLive byte) {
pc.hopsToLive = hopsToLive
}
func (pc *PacketConn) GetHopsToLive() byte {
return pc.hopsToLive
}
// LocalService returns the local service name of the connection.
func (pc *PacketConn) LocalService() string {
return pc.localService
}
// LocalAddr returns the local address the connection is bound to.
func (pc *PacketConn) LocalAddr() net.Addr {
return Addr{
network: pc.s.GetNetworkName(),
node: pc.s.NodeID(),
service: pc.localService,
}
}
// Close closes the connection.
func (pc *PacketConn) Close() error {
pc.s.GetListenerLock().Lock()
defer pc.s.GetListenerLock().Unlock()
delete(pc.s.GetListenerRegistry(), pc.localService)
if pc.cancel != nil {
pc.cancel()
}
if pc.advertise {
err := pc.s.RemoveLocalServiceAdvertisement(pc.localService)
if err != nil {
return err
}
}
return nil
}
// SetDeadline sets both the read and write deadlines.
func (pc *PacketConn) SetDeadline(t time.Time) error {
pc.readDeadlineMutex.Lock()
pc.readDeadline = t
pc.readDeadlineMutex.Unlock()
return nil
}
// SetReadDeadline sets the read deadline.
func (pc *PacketConn) SetReadDeadline(t time.Time) error {
pc.readDeadlineMutex.Lock()
pc.readDeadline = t
pc.readDeadlineMutex.Unlock()
return nil
}
func (pc *PacketConn) GetReadDeadline() time.Time {
pc.readDeadlineMutex.Lock()
readDeadline := pc.readDeadline
pc.readDeadlineMutex.Unlock()
return readDeadline
}
// SetWriteDeadline sets the write deadline.
func (pc *PacketConn) SetWriteDeadline(_ time.Time) error {
// Write deadline doesn't mean anything because Write() implementation is non-blocking.
return nil
}