This repository has been archived by the owner on Sep 4, 2018. It is now read-only.
/
learning.go
95 lines (85 loc) · 1.93 KB
/
learning.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
package switching
import (
bh "github.com/kandoo/beehive"
"github.com/1995parham/flynest/nom"
"github.com/kandoo/beehive/Godeps/_workspace/src/github.com/golang/glog"
)
type LearningSwitch struct {
Hub
}
func (h LearningSwitch) Rcv(msg bh.Msg, ctx bh.RcvContext) error {
in := msg.Data().(nom.PacketIn)
src := in.Packet.SrcMAC()
dst := in.Packet.DstMAC()
glog.V(2).Infof("received packet in from %v to %v", src, dst)
if dst.IsLLDP() {
// TODO(soheil): just drop LLDP.
glog.Infof("dropped LLDP packet to %v", dst)
return nil
}
if dst.IsBroadcast() || dst.IsMulticast() {
return h.Hub.Rcv(msg, ctx)
}
d := ctx.Dict("mac2port")
srck := src.Key()
update := false
if v, err := d.Get(srck); err == nil {
p := v.(nom.UID)
if p != in.InPort {
update = true
// TODO(soheil): maybe add support for multi ports.
glog.Infof("%v is moved from port %v to port %v", src, p, in.InPort)
}
} else {
update = true
}
if update {
if err := d.Put(srck, in.InPort); err != nil {
glog.Fatalf("cannot serialize port: %v", err)
}
}
dstk := dst.Key()
v, err := d.Get(dstk)
if err != nil {
return h.Hub.Rcv(msg, ctx)
}
p := v.(nom.UID)
add := nom.AddFlowEntry{
Flow: nom.FlowEntry{
Node: in.Node,
Match: nom.Match{
Fields: []nom.Field{
nom.EthDst{
Addr: dst,
Mask: nom.MaskNoneMAC,
},
},
},
Actions: []nom.Action{
nom.ActionForward{
Ports: []nom.UID{p},
},
},
},
}
ctx.Reply(msg, add)
out := nom.PacketOut{
Node: in.Node,
InPort: in.InPort,
BufferID: in.BufferID,
Packet: in.Packet,
Actions: []nom.Action{
nom.ActionForward{
Ports: []nom.UID{p},
},
},
}
ctx.Reply(msg, out)
return nil
}
// RegisterSwitch registers the learning switch application on the given
// hive with the provided options.
func RegisterSwitch(h bh.Hive, opts ...bh.AppOption) {
app := h.NewApp("Switch", opts...)
app.Handle(nom.PacketIn{}, LearningSwitch{})
}