forked from contiv/libOpenflow
-
Notifications
You must be signed in to change notification settings - Fork 16
/
stream.go
195 lines (175 loc) · 4.28 KB
/
stream.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
package util
import (
"bytes"
"encoding/binary"
"net"
"strings"
"k8s.io/klog/v2"
)
const numParserGoroutines = 25
type BufferPool struct {
Empty chan *bytes.Buffer
}
func NewBufferPool() *BufferPool {
m := new(BufferPool)
m.Empty = make(chan *bytes.Buffer, 50)
for i := 0; i < 50; i++ {
m.Empty <- bytes.NewBuffer(make([]byte, 0, 2048))
}
return m
}
// Parser interface
type Parser interface {
Parse(b []byte) (message Message, err error)
}
type streamWorker struct {
Full chan *bytes.Buffer
}
func (w *streamWorker) parse(stopCh chan bool, parser Parser, inbound chan Message, empty chan *bytes.Buffer) {
for {
select {
case b := <-w.Full:
msg, err := parser.Parse(b.Bytes())
// Log all message parsing errors.
if err != nil {
klog.ErrorS(err, "Failed to parse received message", "bytes", b.Bytes())
} else {
inbound <- msg
}
b.Reset()
empty <- b
case <-stopCh:
return
}
}
}
type MessageStream struct {
conn net.Conn
pool *BufferPool
// Message parser
parser Parser
// Channel to shut down the parser goroutine
parserShutdown chan bool
// OpenFlow Version
Version uint8
// Channel on which to publish connection errors
Error chan error
// Channel on which to publish inbound messages
Inbound chan Message
// Channel on which to receive outbound messages
Outbound chan Message
// Channel on which to receive a shutdown command
Shutdown chan bool
// Worker to parse the message received from the connection
workers []streamWorker
}
// Returns a pointer to a new MessageStream. Used to parse
// OpenFlow messages from conn.
func NewMessageStream(conn net.Conn, parser Parser) *MessageStream {
m := &MessageStream{
conn,
NewBufferPool(),
parser,
make(chan bool, 1),
0,
make(chan error, 1), // Error
make(chan Message, 1), // Inbound
make(chan Message, 1), // Outbound
make(chan bool, 1), // Shutdown
make([]streamWorker, numParserGoroutines),
}
for i := 0; i < numParserGoroutines; i++ {
worker := streamWorker{
Full: make(chan *bytes.Buffer),
}
m.workers[i] = worker
go worker.parse(m.parserShutdown, m.parser, m.Inbound, m.pool.Empty)
}
go m.outbound()
go m.inbound()
return m
}
func (m *MessageStream) GetAddr() net.Addr {
return m.conn.RemoteAddr()
}
// Listen for a Shutdown signal or Outbound messages.
func (m *MessageStream) outbound() {
for {
select {
case <-m.Shutdown:
klog.Infof("Closing OpenFlow message stream.")
m.conn.Close()
close(m.parserShutdown)
return
case msg := <-m.Outbound:
// Forward outbound messages to conn
data, _ := msg.MarshalBinary()
if _, err := m.conn.Write(data); err != nil {
klog.ErrorS(err, "OutboundError")
m.Error <- err
m.Shutdown <- true
}
// Only log the data with loglevel >= 7.
if klogV := klog.V(7); klogV.Enabled() {
klogV.InfoS("Sent outbound message", "dataLength", len(data), "data", data)
} else {
klog.V(4).InfoS("Sent outbound message", "dataLength", len(data))
}
}
}
}
// Handle inbound messages
func (m *MessageStream) inbound() {
msgLen := 0
hdr := 0
hdrBuf := make([]byte, 4)
tmpBuf := make([]byte, 2048)
buf := <-m.pool.Empty
for {
n, err := m.conn.Read(tmpBuf)
if err != nil {
// Handle explicitly disconnecting by closing connection
if strings.Contains(err.Error(), "use of closed network connection") {
return
}
klog.ErrorS(err, "InboundError")
m.Error <- err
m.Shutdown <- true
return
}
for i := 0; i < n; i++ {
if hdr < 4 {
hdrBuf[hdr] = tmpBuf[i]
buf.WriteByte(tmpBuf[i])
hdr += 1
if hdr >= 4 {
// MessageStream is not protocol agnostic. Reading length based
// on OpenFlow header field.
msgLen = int(binary.BigEndian.Uint16(hdrBuf[2:])) - 4
}
continue
}
if msgLen > 0 {
buf.WriteByte(tmpBuf[i])
msgLen = msgLen - 1
if msgLen == 0 {
hdr = 0
m.dispatchMessage(buf)
buf = <-m.pool.Empty
}
continue
}
}
}
}
// Dispatch the message to streamWorker according to Xid in the message Header
func (m *MessageStream) dispatchMessage(b *bytes.Buffer) {
msgBytes := b.Bytes()
if len(msgBytes) < 8 {
klog.Error("Buffer too small to parse OpenFlow messages")
return
}
xid := binary.BigEndian.Uint32(msgBytes[4:])
workerKey := int(xid % uint32(len(m.workers)))
m.workers[workerKey].Full <- b
}