forked from contiv/ofnet
-
Notifications
You must be signed in to change notification settings - Fork 16
/
ofctrl.go
329 lines (278 loc) · 8.37 KB
/
ofctrl.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
317
318
319
320
321
322
323
324
325
326
327
328
329
/***
Copyright 2014 Cisco Systems Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ofctrl
// This library implements a simple openflow 1.3 controller
import (
"fmt"
"math/rand"
"net"
"strings"
"sync"
"time"
"antrea.io/libOpenflow/common"
"antrea.io/libOpenflow/openflow13"
"antrea.io/libOpenflow/util"
log "github.com/sirupsen/logrus"
)
type PacketIn openflow13.PacketIn
// Note: Command to make ovs connect to controller:
// ovs-vsctl set-controller <bridge-name> tcp:<ip-addr>:<port>
// E.g. sudo ovs-vsctl set-controller ovsbr0 tcp:127.0.0.1:6633
// To enable openflow1.3 support in OVS:
// ovs-vsctl set bridge <bridge-name> protocols=OpenFlow10,OpenFlow11,OpenFlow12,OpenFlow13
// E.g. sudo ovs-vsctl set bridge ovsbr0 protocols=OpenFlow10,OpenFlow11,OpenFlow12,OpenFlow13
type AppInterface interface {
// A Switch connected to the controller
SwitchConnected(sw *OFSwitch)
// Switch disconnected from the controller
SwitchDisconnected(sw *OFSwitch)
// Controller received a packet from the switch
PacketRcvd(sw *OFSwitch, pkt *PacketIn)
// Controller received a multi-part reply from the switch
MultipartReply(sw *OFSwitch, rep *openflow13.MultipartReply)
}
type ConnectionRetryControl interface {
MaxRetry() int
RetryInterval() time.Duration
}
type ConnectionMode int
const (
ServerMode ConnectionMode = iota
ClientMode
maxRetryForConnection = 10
)
// Connection operation type
const (
InitConnection = iota
ReConnection
CompleteConnection
)
type Controller struct {
app AppInterface
listener *net.TCPListener
wg sync.WaitGroup
connectMode ConnectionMode
connCh chan int // Channel to control the UDS connection between controller and OFSwitch
exitCh chan struct{} // Channel to stop the Controller
id uint16
}
// Create a new controller
func NewController(app AppInterface) *Controller {
c := new(Controller)
c.connectMode = ServerMode
c.id = uint16(rand.Uint32()) // #nosec G404: random number generator not used for security purposes
// for debug logs
// log.SetLevel(log.DebugLevel)
// Save the handler
c.app = app
c.exitCh = make(chan struct{})
return c
}
// Listen on a port
func (c *Controller) Listen(port string) {
addr, _ := net.ResolveTCPAddr("tcp", port)
var err error
c.listener, err = net.ListenTCP("tcp", addr)
if err != nil {
log.Fatal(err)
}
defer c.listener.Close()
log.Println("Listening for connections on", addr)
for {
conn, err := c.listener.AcceptTCP()
if err != nil {
if strings.Contains(err.Error(), "use of closed network connection") {
return
}
log.Fatal(err)
}
c.wg.Add(1)
go c.handleConnection(conn)
}
}
// Linux: Connect to Unix Domain Socket file
// Windows: Connect to named pipe
func (c *Controller) Connect(sock string) error {
if c.connCh == nil {
// Construct stop flag for notifying controller to stop connections
c.connCh = make(chan int)
// Reset connection mode as ClientMode
c.connectMode = ClientMode
// Setup initial connection
go func() {
c.connCh <- InitConnection
}()
}
var conn net.Conn
defer func() {
if conn != nil {
conn.Close()
}
}()
// Parse retry configuration.
var maxRetry = maxRetryForConnection
var retryInterval = 1 * time.Second
if retryController, ok := c.app.(ConnectionRetryControl); ok {
maxRetry = retryController.MaxRetry()
retryInterval = retryController.RetryInterval()
}
for {
select {
case connCtrl := <-c.connCh:
switch connCtrl {
case InitConnection:
fallthrough
case ReConnection:
log.Infof("Initialize connection or re-connect to %s.", sock)
if conn != nil {
// Try to close the existing connection
_ = conn.Close()
}
// Retry to connect to the switch if hit error.
conn, err := c.getConnection(sock, maxRetry, retryInterval)
if err != nil {
return err
}
maxRetry = 0
c.wg.Add(1)
log.Printf("Connected to socket %s", sock)
go c.handleConnection(conn)
case CompleteConnection:
continue
}
case <-c.exitCh:
log.Println("Controller is delete")
return nil
}
}
}
func (c *Controller) getConnection(address string, maxRetry int, retryInterval time.Duration) (net.Conn, error) {
var count int
for {
select {
case <-time.After(retryInterval):
// Linux: Connect to Unix Domain Socket file
// Windows: Connect to named pipe
conn, err := DialUnixOrNamedPipe(address)
if err == nil {
return conn, nil
}
count++
// Check if the re-connection times come to the max value, if true, return the error.
// If it is required to re-connect until the Switch is connected, or the retry times it don't
// come the max value, continually retry.
if maxRetry > 0 && count == maxRetry {
return nil, err
}
log.Errorf("Failed to connect to %s, retry after %s: %v.", address, retryInterval.String(), err)
case <-c.exitCh:
log.Info("Controller is deleted, stop re-connections")
return nil, fmt.Errorf("controller is deleted, and connection is set as nil")
}
}
}
// Cleanup the controller
func (c *Controller) Delete() {
if c.connectMode == ServerMode {
c.listener.Close()
} else if c.connectMode == ClientMode {
// Send signal to stop connections to the switch
close(c.exitCh)
}
c.wg.Wait()
c.app = nil
}
// Handle TCP connection from the switch
func (c *Controller) handleConnection(conn net.Conn) {
var connFlag int = CompleteConnection
defer func() {
c.connCh <- connFlag
}()
defer c.wg.Done()
stream := util.NewMessageStream(conn, c)
log.Println("New connection..")
// Send ofp 1.3 Hello by default
h, err := common.NewHello(4)
if err != nil {
return
}
log.Printf("Send hello with OF version: %d", h.Version)
stream.Outbound <- h
for {
select {
// Send hello message with latest protocol version.
case msg := <-stream.Inbound:
switch m := msg.(type) {
// A Hello message of the appropriate type
// completes version negotiation. If version
// types are incompatible, it is possible the
// connection may be servered without error.
case *common.Hello:
if m.Version == openflow13.VERSION {
log.Infoln("Received Openflow 1.3 Hello message")
// Version negotiation is
// considered complete. Create
// new Switch and notifiy listening
// applications.
stream.Version = m.Version
stream.Outbound <- openflow13.NewFeaturesRequest()
} else {
// Connection should be severed if controller
// doesn't support switch version.
log.Println("Received unsupported ofp version", m.Version)
stream.Shutdown <- true
}
// After a vaild FeaturesReply has been received we
// have all the information we need. Create a new
// switch object and notify applications.
case *openflow13.SwitchFeatures:
log.Printf("Received ofp1.3 Switch feature response: %+v", *m)
// Create a new switch and handover the stream
var reConnChan chan int = nil
if c.connectMode == ClientMode {
reConnChan = c.connCh
}
NewSwitch(stream, m.DPID, c.app, reConnChan, c.id)
// Let switch instance handle all future messages..
return
// An error message may indicate a version mismatch. We
// disconnect if an error occurs this early.
case *openflow13.ErrorMsg:
log.Warnf("Received OpenFlow error msg: %+v", *m)
stream.Shutdown <- true
}
case err := <-stream.Error:
// The connection has been shutdown.
log.Println(err)
connFlag = ReConnection
return
case <-time.After(heartbeatInterval):
// This shouldn't happen. If it does, both the controller
// and switch are no longer communicating. The TCPConn is
// still established though.
log.Warnln("Connection timed out.")
connFlag = ReConnection
return
}
}
}
// Demux based on message version
func (c *Controller) Parse(b []byte) (message util.Message, err error) {
switch b[0] {
case openflow13.VERSION:
message, err = openflow13.Parse(b)
default:
log.Errorf("Received unsupported OpenFlow version: %d", b[0])
}
return
}