-
Notifications
You must be signed in to change notification settings - Fork 81
/
packetconn.go
235 lines (210 loc) · 5.92 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
package netceptor
import (
"context"
"fmt"
"net"
"reflect"
"time"
"github.com/ansible/receptor/pkg/utils"
)
// PacketConn implements the net.PacketConn interface via the Receptor network.
type PacketConn struct {
s *Netceptor
localService string
recvChan chan *MessageData
readDeadline time.Time
advertise bool
adTags map[string]string
connType byte
hopsToLive byte
unreachableSubs *utils.Broker
context context.Context
cancel context.CancelFunc
}
// 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) (*PacketConn, 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 := &PacketConn{
s: s,
localService: service,
recvChan: make(chan *MessageData),
advertise: false,
adTags: nil,
connType: ConnTypeDatagram,
hopsToLive: s.maxForwardingHops,
}
pc.startUnreachable()
s.listenerRegistry[service] = pc
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) (*PacketConn, error) {
pc, err := s.ListenPacket(service)
if err != nil {
return nil, err
}
pc.advertise = true
pc.adTags = tags
s.addLocalServiceAdvertisement(service, ConnTypeDatagram, tags)
return pc, nil
}
// 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.unreachableBroker.Subscribe()
go func() {
<-pc.context.Done()
pc.s.unreachableBroker.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.readDeadline.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.readDeadline)):
return 0, nil, ErrTimeout
}
}
if m == nil {
return 0, nil, fmt.Errorf("connection closed")
}
nCopied := copy(p, m.Data)
fromAddr := Addr{
network: pc.s.networkName,
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
}
// 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.networkName,
node: pc.s.nodeID,
service: pc.localService,
}
}
// Close closes the connection.
func (pc *PacketConn) Close() error {
pc.s.listenerLock.Lock()
defer pc.s.listenerLock.Unlock()
delete(pc.s.listenerRegistry, 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.readDeadline = t
return nil
}
// SetReadDeadline sets the read deadline.
func (pc *PacketConn) SetReadDeadline(t time.Time) error {
pc.readDeadline = t
return nil
}
// 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
}