forked from contiv/libOpenflow
-
Notifications
You must be signed in to change notification settings - Fork 17
/
stream.go
189 lines (169 loc) · 3.98 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
package util
import (
"bytes"
"encoding/binary"
"net"
"strings"
log "github.com/sirupsen/logrus"
)
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) {
errMessage := "received: %v and encountered error: %v"
for {
select {
case b := <-w.Full:
msg, err := parser.Parse(b.Bytes())
// Log all message parsing errors.
if err != nil {
log.Errorf(errMessage, b.Bytes(), err)
} 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:
log.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 {
log.Warnln("OutboundError:", err)
m.Error <- err
m.Shutdown <- true
}
log.Debugf("Sent(%d): %v", len(data), data)
}
}
}
// Handle inbound messages
func (m *MessageStream) inbound() {
msg := 0
hdr := 0
hdrBuf := make([]byte, 4)
tmp := make([]byte, 2048)
buf := <-m.pool.Empty
for {
n, err := m.conn.Read(tmp)
if err != nil {
// Handle explicitly disconnecting by closing connection
if strings.Contains(err.Error(), "use of closed network connection") {
return
}
log.Warnln("InboundError", err)
m.Error <- err
m.Shutdown <- true
return
}
for i := 0; i < n; i++ {
if hdr < 4 {
hdrBuf[hdr] = tmp[i]
buf.WriteByte(tmp[i])
hdr += 1
if hdr >= 4 {
msg = int(binary.BigEndian.Uint16(hdrBuf[2:])) - 4
}
continue
}
if msg > 0 {
buf.WriteByte(tmp[i])
msg = msg - 1
if msg == 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 {
log.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
}