This repository has been archived by the owner on Apr 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
controller.go
110 lines (94 loc) · 2.31 KB
/
controller.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
// Copyright 2017 Politecnico di Torino
//
// 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 hover
import (
"encoding/gob"
"fmt"
"net"
"io"
)
type SlowPathCallBack func(*PacketIn) (error)
type PacketInMd struct {
Module_id uint16
Port_id uint16
Packet_len uint32
Reason uint16
Metadata [3]uint32
}
type PacketIn struct {
Md PacketInMd
Data []byte
}
const (
INGRESS = 0
EGRESS = 1
)
type PacketOut struct {
Module_id uint16
Port_id uint16
Sense uint16 /* ingress = 0, egress = 1 */
Data []byte
}
func (p *PacketIn) ToString() string {
return fmt.Sprintf("Module_id: %d\nPort_id: %d\nPacket_len: %d\nReason: %d\n",
p.Md.Module_id, p.Md.Port_id, p.Md.Packet_len, p.Md.Reason)
}
type Controller struct {
callbacks map[uint16]SlowPathCallBack
listenaddr string
conn net.Conn
}
func (c *Controller) Init(listenaddr string) (err error) {
c.callbacks = make(map[uint16]SlowPathCallBack)
c.listenaddr = listenaddr
return nil
}
func (c *Controller) RegisterCallBack(id uint16, cb SlowPathCallBack) (err error) {
c.callbacks[id] = cb
return nil
}
func (c *Controller) Run() (err error) {
ln, err1 := net.Listen("tcp", c.listenaddr)
if err1 != nil {
return err1
}
c.conn, err = ln.Accept()
if err != nil {
return
}
dec := gob.NewDecoder(c.conn)
log.Infof("Controller: New client connected")
for {
p := &PacketIn{}
err1 := dec.Decode(p)
if err1 == io.EOF {
log.Info("Controller: Client Disconnected")
return nil
} else if err1 != nil {
continue
}
//log.Info("Packet arrived: ", p.ToString())
cb, ok := c.callbacks[p.Md.Module_id]
if !ok {
log.Infof("Controller: Callback not found")
continue
}
cb(p)
}
}
func (c *Controller) SendPacketOut(p *PacketOut) (err error) {
encoder := gob.NewEncoder(c.conn)
encoder.Encode(p)
return
}